/
kms.go
60 lines (53 loc) · 1.3 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
package aws
import (
b64 "github.com/hairyhenderson/gomplate/v3/base64"
"github.com/aws/aws-sdk-go/service/kms"
)
// KMSAPI is a subset of kmsiface.KMSAPI
type KMSAPI interface {
Encrypt(input *kms.EncryptInput) (*kms.EncryptOutput, error)
Decrypt(input *kms.DecryptInput) (*kms.DecryptOutput, error)
}
// KMS is an AWS KMS client
type KMS struct {
Client KMSAPI
}
// NewKMS - Create new AWS KMS client using an SDKSession
func NewKMS(_ ClientOptions) *KMS {
client := kms.New(SDKSession())
return &KMS{
Client: client,
}
}
// Encrypt plaintext using the specified key.
// Returns a base64 encoded ciphertext
func (k *KMS) Encrypt(keyID, plaintext string) (string, error) {
input := &kms.EncryptInput{
KeyId: &keyID,
Plaintext: []byte(plaintext),
}
output, err := k.Client.Encrypt(input)
if err != nil {
return "", err
}
ciphertext, err := b64.Encode(output.CiphertextBlob)
if err != nil {
return "", err
}
return ciphertext, nil
}
// Decrypt a base64 encoded ciphertext
func (k *KMS) Decrypt(ciphertext string) (string, error) {
ciphertextBlob, err := b64.Decode(ciphertext)
if err != nil {
return "", err
}
input := &kms.DecryptInput{
CiphertextBlob: ciphertextBlob,
}
output, err := k.Client.Decrypt(input)
if err != nil {
return "", err
}
return string(output.Plaintext), nil
}