signer.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package cloudkms
  2. import (
  3. "crypto"
  4. "crypto/x509"
  5. "io"
  6. "github.com/pkg/errors"
  7. "go.step.sm/crypto/pemutil"
  8. kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
  9. )
  10. // Signer implements a crypto.Signer using Google's Cloud KMS.
  11. type Signer struct {
  12. client KeyManagementClient
  13. signingKey string
  14. algorithm x509.SignatureAlgorithm
  15. publicKey crypto.PublicKey
  16. }
  17. // NewSigner creates a new crypto.Signer the given CloudKMS signing key.
  18. func NewSigner(c KeyManagementClient, signingKey string) (*Signer, error) {
  19. // Make sure that the key exists.
  20. signer := &Signer{
  21. client: c,
  22. signingKey: signingKey,
  23. }
  24. if err := signer.preloadKey(signingKey); err != nil {
  25. return nil, err
  26. }
  27. return signer, nil
  28. }
  29. func (s *Signer) preloadKey(signingKey string) error {
  30. ctx, cancel := defaultContext()
  31. defer cancel()
  32. response, err := s.client.GetPublicKey(ctx, &kmspb.GetPublicKeyRequest{
  33. Name: signingKey,
  34. })
  35. if err != nil {
  36. return errors.Wrap(err, "cloudKMS GetPublicKey failed")
  37. }
  38. s.algorithm = cryptoKeyVersionMapping[response.Algorithm]
  39. s.publicKey, err = pemutil.ParseKey([]byte(response.Pem))
  40. return err
  41. }
  42. // Public returns the public key of this signer or an error.
  43. func (s *Signer) Public() crypto.PublicKey {
  44. return s.publicKey
  45. }
  46. // Sign signs digest with the private key stored in Google's Cloud KMS.
  47. func (s *Signer) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
  48. req := &kmspb.AsymmetricSignRequest{
  49. Name: s.signingKey,
  50. Digest: &kmspb.Digest{},
  51. }
  52. switch h := opts.HashFunc(); h {
  53. case crypto.SHA256:
  54. req.Digest.Digest = &kmspb.Digest_Sha256{
  55. Sha256: digest,
  56. }
  57. case crypto.SHA384:
  58. req.Digest.Digest = &kmspb.Digest_Sha384{
  59. Sha384: digest,
  60. }
  61. case crypto.SHA512:
  62. req.Digest.Digest = &kmspb.Digest_Sha512{
  63. Sha512: digest,
  64. }
  65. default:
  66. return nil, errors.Errorf("unsupported hash function %v", h)
  67. }
  68. ctx, cancel := defaultContext()
  69. defer cancel()
  70. response, err := s.client.AsymmetricSign(ctx, req)
  71. if err != nil {
  72. return nil, errors.Wrap(err, "cloudKMS AsymmetricSign failed")
  73. }
  74. return response.Signature, nil
  75. }
  76. // SignatureAlgorithm returns the algorithm that must be specified in a
  77. // certificate to sign. This is specially important to distinguish RSA and
  78. // RSAPSS schemas.
  79. func (s *Signer) SignatureAlgorithm() x509.SignatureAlgorithm {
  80. return s.algorithm
  81. }