-
Notifications
You must be signed in to change notification settings - Fork 3
/
aws.go
105 lines (84 loc) · 2.52 KB
/
aws.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
package secrets
import (
"context"
"encoding/base64"
"log"
"sync"
"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"
"github.com/pkg/errors"
)
// AwsKeyService represents connection to Amazon Web Services KMS
type AwsKeyService struct {
region string
masterKeyID string
service *kms.Client
sync.RWMutex
}
// NewAwsKeyService creates a new AwsKeyService in given AWS region and with the given masterKey identifier.
func NewAwsKeyService(region string, masterKeyID string) *AwsKeyService {
return &AwsKeyService{
region: region,
masterKeyID: masterKeyID,
}
}
func awsSession(region string) (aws.Config, error) {
return config.LoadDefaultConfig(context.TODO(), config.WithRegion(region), config.WithSharedConfigProfile(""))
}
func (s *AwsKeyService) setup() error {
s.Lock()
defer s.Unlock()
if s.service == nil {
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(s.region))
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
s.service = kms.NewFromConfig(cfg)
}
return nil
}
// GenerateKey generates a brand new ServerKey.
func (s *AwsKeyService) GenerateKey(kid string) (*EncryptionKey, error) {
if err := s.setup(); err != nil {
return nil, errors.Wrapf(err, "failed to setup")
}
input := &kms.GenerateDataKeyInput{
EncryptionContext: map[string]string{"kid": kid},
GrantTokens: []string{"Encrypt", "Decrypt"},
KeyId: aws.String(s.masterKeyID),
KeySpec: "AES_256",
}
out, err := s.service.GenerateDataKey(context.TODO(), input)
if err != nil {
return nil, errors.Wrapf(err, "failed to GenerateDataKey")
}
result := &EncryptionKey{
KID: kid,
Enc: A256GCM,
RawKey: out.Plaintext,
EncKey: base64.RawURLEncoding.EncodeToString(out.CiphertextBlob),
}
return result, nil
}
// DecryptKey decrypts an existing ServerKey.
func (s *AwsKeyService) DecryptKey(key *EncryptionKey) error {
if err := s.setup(); err != nil {
return errors.Wrapf(err, "failed to setup")
}
ciphertextBlob, err := base64.RawURLEncoding.DecodeString(key.EncKey)
if err != nil {
return errors.Wrap(err, "failed to DecodeString")
}
input := &kms.DecryptInput{
CiphertextBlob: ciphertextBlob,
EncryptionContext: map[string]string{"kid": key.KID},
GrantTokens: []string{"Encrypt", "Decrypt"},
}
out, err := s.service.Decrypt(context.TODO(), input)
if err != nil {
return errors.Wrapf(err, "failed to Decrypt")
}
key.RawKey = out.Plaintext
return nil
}