-
Notifications
You must be signed in to change notification settings - Fork 0
/
kms.go
102 lines (84 loc) · 2.59 KB
/
kms.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
package internal
import (
"context"
"errors"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/kms"
kmsTypes "github.com/aws/aws-sdk-go-v2/service/kms/types"
"os/signal"
"syscall"
)
var (
algorithmSpecs = map[string]kmsTypes.SigningAlgorithmSpec{
"PS256": kmsTypes.SigningAlgorithmSpecRsassaPssSha256,
"PS384": kmsTypes.SigningAlgorithmSpecRsassaPssSha384,
"PS512": kmsTypes.SigningAlgorithmSpecRsassaPssSha512,
"RS256": kmsTypes.SigningAlgorithmSpecRsassaPkcs1V15Sha256,
"RS384": kmsTypes.SigningAlgorithmSpecRsassaPkcs1V15Sha384,
"RS512": kmsTypes.SigningAlgorithmSpecRsassaPkcs1V15Sha512,
"ES256": kmsTypes.SigningAlgorithmSpecEcdsaSha256,
"ES384": kmsTypes.SigningAlgorithmSpecEcdsaSha384,
"ES512": kmsTypes.SigningAlgorithmSpecEcdsaSha512,
}
)
func GetAlgorithmSpec(alg string) kmsTypes.SigningAlgorithmSpec {
return algorithmSpecs[alg]
}
type KmsSignerVerifier interface {
Sign(alg kmsTypes.SigningAlgorithmSpec, msg string) (string, error)
Verify(alg kmsTypes.SigningAlgorithmSpec, msg string, sig string) error
}
func NewKmsSignerVerifier(keyID string) (k KmsSignerVerifier, err error) {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
stop()
return
}
client := kms.NewFromConfig(cfg)
k = kmsSignerVerifier{KeyID: keyID, client: client}
return
}
type kmsSignerVerifier struct {
KeyID string
client *kms.Client
}
func (k kmsSignerVerifier) Sign(alg kmsTypes.SigningAlgorithmSpec, msg string) (signature string, err error) {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
params := &kms.SignInput{
KeyId: aws.String(k.KeyID),
Message: []byte(msg),
MessageType: kmsTypes.MessageTypeRaw,
SigningAlgorithm: alg,
}
resp, err := k.client.Sign(ctx, params)
if err != nil {
stop()
return
}
signature = string(resp.Signature)
return
}
func (k kmsSignerVerifier) Verify(alg kmsTypes.SigningAlgorithmSpec, msg string, sig string) (err error) {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
params := &kms.VerifyInput{
KeyId: aws.String(k.KeyID),
Message: []byte(msg),
MessageType: kmsTypes.MessageTypeRaw,
Signature: []byte(sig),
SigningAlgorithm: alg,
}
resp, err := k.client.Verify(ctx, params)
if err != nil {
stop()
return
}
if !resp.SignatureValid {
err = errors.New("invalid signature")
}
return
}