/
crypter.go
53 lines (41 loc) · 1.21 KB
/
crypter.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
package aws
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/kms"
"github.com/aws/aws-sdk-go-v2/service/kms/types"
)
type AWSKMSCrypter struct {
keyARN string
}
func NewAWSKMSCrypter(key []byte) *AWSKMSCrypter {
return &AWSKMSCrypter{keyARN: string(key)}
}
func (c *AWSKMSCrypter) Encrypt(message []byte) (encrypted []byte, err error) {
ctx := context.Background()
client := createKMSClient(ctx)
encryptOutput, err := client.Encrypt(ctx, &kms.EncryptInput{
KeyId: aws.String(c.keyARN),
Plaintext: message,
EncryptionAlgorithm: types.EncryptionAlgorithmSpecSymmetricDefault,
})
if err != nil {
return encrypted, err
}
encrypted = encryptOutput.CiphertextBlob
return encrypted, err
}
func (c *AWSKMSCrypter) Decrypt(encrypted []byte) (message []byte, err error) {
ctx := context.Background()
client := createKMSClient(ctx)
decryptOutput, err := client.Decrypt(ctx, &kms.DecryptInput{
KeyId: aws.String(c.keyARN),
CiphertextBlob: encrypted,
EncryptionAlgorithm: types.EncryptionAlgorithmSpecSymmetricDefault,
})
if err != nil {
return message, err
}
message = decryptOutput.Plaintext
return message, err
}