-
Notifications
You must be signed in to change notification settings - Fork 0
/
signer.go
106 lines (90 loc) · 2.55 KB
/
signer.go
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
99
100
101
102
103
104
105
106
package cloudkms
import (
"context"
"crypto"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"time"
kms "cloud.google.com/go/kms/apiv1"
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)
// Signer implements crypto.Signer interface.
type Signer struct {
keyPath string
client *kms.KeyManagementClient
signTimeout time.Duration
algorithm kmspb.CryptoKeyVersion_CryptoKeyVersionAlgorithm
pubKey crypto.PublicKey
}
func NewSigner(client *kms.KeyManagementClient, keyPath string) (*Signer, error) {
ctx := context.Background()
ctx, _ = context.WithTimeout(ctx, 10*time.Second)
pubKeypb, err := client.GetPublicKey(ctx, &kmspb.GetPublicKeyRequest{
Name: keyPath,
})
if err != nil {
return nil, fmt.Errorf("failed to get public key: %s", err)
}
block, _ := pem.Decode([]byte(pubKeypb.Pem))
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %s", err)
}
return &Signer{
keyPath: keyPath,
client: client,
signTimeout: 15 * time.Second,
algorithm: pubKeypb.Algorithm,
pubKey: pubKey,
}, nil
}
func (s *Signer) Public() crypto.PublicKey {
return s.pubKey
}
func (s *Signer) HashFunc() crypto.Hash {
switch s.algorithm {
case kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_3072_SHA256,
kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA256,
kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256:
return crypto.SHA256
case kmspb.CryptoKeyVersion_EC_SIGN_P384_SHA384:
return crypto.SHA384
default:
return 0
}
}
func (s *Signer) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) {
ctx := context.Background()
ctx, _ = context.WithTimeout(context.Background(), s.signTimeout)
var kmsDigest *kmspb.Digest
switch s.algorithm {
case kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_3072_SHA256,
kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_4096_SHA256,
kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256:
kmsDigest = &kmspb.Digest{
Digest: &kmspb.Digest_Sha256{
Sha256: digest,
},
}
case kmspb.CryptoKeyVersion_EC_SIGN_P384_SHA384:
kmsDigest = &kmspb.Digest{
Digest: &kmspb.Digest_Sha384{
Sha384: digest,
},
}
default:
return nil, fmt.Errorf("not implemented yet: %s", s.algorithm.String())
}
res, err := s.client.AsymmetricSign(ctx, &kmspb.AsymmetricSignRequest{
Name: s.keyPath,
Digest: kmsDigest,
})
if err != nil {
return nil, fmt.Errorf("failed to sign: %s", err)
}
return res.GetSignature(), nil
}