File: signer.go

package info (click to toggle)
golang-github-smallstep-crypto 0.57.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,284 kB
  • sloc: sh: 53; makefile: 36
file content (98 lines) | stat: -rw-r--r-- 2,392 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//go:build !nocloudkms
// +build !nocloudkms

package cloudkms

import (
	"crypto"
	"crypto/x509"
	"io"

	"cloud.google.com/go/kms/apiv1/kmspb"
	"github.com/pkg/errors"
	"go.step.sm/crypto/pemutil"
)

// Signer implements a crypto.Signer using Google's Cloud KMS.
type Signer struct {
	client     KeyManagementClient
	signingKey string
	algorithm  x509.SignatureAlgorithm
	publicKey  crypto.PublicKey
}

// NewSigner creates a new crypto.Signer the given CloudKMS signing key.
func NewSigner(c KeyManagementClient, signingKey string) (*Signer, error) {
	// Make sure that the key exists.
	signer := &Signer{
		client:     c,
		signingKey: resourceName(signingKey),
	}
	if err := signer.preloadKey(); err != nil {
		return nil, err
	}

	return signer, nil
}

func (s *Signer) preloadKey() error {
	ctx, cancel := defaultContext()
	defer cancel()

	response, err := s.client.GetPublicKey(ctx, &kmspb.GetPublicKeyRequest{
		Name: s.signingKey,
	})
	if err != nil {
		return errors.Wrap(err, "cloudKMS GetPublicKey failed")
	}
	s.algorithm = cryptoKeyVersionMapping[response.Algorithm]
	s.publicKey, err = pemutil.ParseKey([]byte(response.Pem))
	return err
}

// Public returns the public key of this signer or an error.
func (s *Signer) Public() crypto.PublicKey {
	return s.publicKey
}

// Sign signs digest with the private key stored in Google's Cloud KMS.
func (s *Signer) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
	req := &kmspb.AsymmetricSignRequest{
		Name:   s.signingKey,
		Digest: &kmspb.Digest{},
	}

	switch h := opts.HashFunc(); h {
	case crypto.SHA256:
		req.Digest.Digest = &kmspb.Digest_Sha256{
			Sha256: digest,
		}
	case crypto.SHA384:
		req.Digest.Digest = &kmspb.Digest_Sha384{
			Sha384: digest,
		}
	case crypto.SHA512:
		req.Digest.Digest = &kmspb.Digest_Sha512{
			Sha512: digest,
		}
	default:
		return nil, errors.Errorf("unsupported hash function %v", h)
	}

	ctx, cancel := defaultContext()
	defer cancel()

	response, err := s.client.AsymmetricSign(ctx, req)
	if err != nil {
		return nil, errors.Wrap(err, "cloudKMS AsymmetricSign failed")
	}

	return response.Signature, nil
}

// SignatureAlgorithm returns the algorithm that must be specified in a
// certificate to sign. This is specially important to distinguish RSA and
// RSAPSS schemas.
func (s *Signer) SignatureAlgorithm() x509.SignatureAlgorithm {
	return s.algorithm
}