-
Notifications
You must be signed in to change notification settings - Fork 39
/
kms.go
73 lines (57 loc) · 1.72 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
package unicreds
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/aws/aws-sdk-go/service/kms/kmsiface"
)
var kmsSvc kmsiface.KMSAPI
func init() {
kmsSvc = kms.New(session.New(), aws.NewConfig())
}
// SetKMSConfig override the default aws configuration
func SetKMSConfig(config *aws.Config) {
kmsSvc = kms.New(session.New(), config)
}
func SetKMSSession(sess *session.Session) {
kmsSvc = kms.New(sess)
}
// DataKey which contains the details of the KMS key
type DataKey struct {
CiphertextBlob []byte
Plaintext []byte
}
// GenerateDataKey simplified method for generating a datakey with kms
func GenerateDataKey(alias string, encContext *EncryptionContextValue, size int) (*DataKey, error) {
numberOfBytes := int64(size)
params := &kms.GenerateDataKeyInput{
KeyId: aws.String(alias),
EncryptionContext: *encContext,
GrantTokens: []*string{},
NumberOfBytes: aws.Int64(numberOfBytes),
}
resp, err := kmsSvc.GenerateDataKey(params)
if err != nil {
return nil, err
}
return &DataKey{
CiphertextBlob: resp.CiphertextBlob,
Plaintext: resp.Plaintext, // return the plain text key after generation
}, nil
}
// DecryptDataKey ask kms to decrypt the supplied data key
func DecryptDataKey(ciphertext []byte, encContext *EncryptionContextValue) (*DataKey, error) {
params := &kms.DecryptInput{
CiphertextBlob: ciphertext,
EncryptionContext: *encContext,
GrantTokens: []*string{},
}
resp, err := kmsSvc.Decrypt(params)
if err != nil {
return nil, err
}
return &DataKey{
CiphertextBlob: ciphertext,
Plaintext: resp.Plaintext, // transfer the plain text key after decryption
}, nil
}