forked from blockpane/ephemera
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kms.go
70 lines (66 loc) · 2.03 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
package sharedpw
import (
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/kms"
)
// GetRandomId returns a 8 byte hex-encoded string that is used for the secret ID.
// This function uses AWS KMS to generate the random value.
func GetRandomId() (string, error) {
result, err := KMS.GenerateRandom(
&kms.GenerateRandomInput{
NumberOfBytes: aws.Int64(8),
},
)
if err != nil {
return "", err
}
return hex.EncodeToString(result.Plaintext), nil
}
// EncryptSecret returns a base64 encrypted string given a base64 plaintext input.
// It enforces a max length of 1024 bytes on the input (after decoding from base64)
func EncryptSecret(b64PlainText string) (string, error) {
decoded, err := base64.StdEncoding.DecodeString(b64PlainText)
switch {
case err != nil:
return "", err
case len(decoded) < 1:
return "", errors.New(`plaintext to encrypt too short`)
case len(decoded) > 4096:
return "", errors.New(`plaintext to encrypt is too long`)
}
out, err := KMS.Encrypt(&kms.EncryptInput{
EncryptionContext: map[string]*string{
`account`: aws.String(AwsAccount),
`application`: aws.String(Application),
},
KeyId: aws.String(fmt.Sprintf("arn:aws:kms:%s:%s:key/%s", Region, AwsAccount, KmsKeyId)),
Plaintext: decoded,
})
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(out.CiphertextBlob), nil
}
// DecryptSecret returns a bas64 encoded string of the plaintext from an encrypted base64 string using the KMS key
// used to encrypt it.
func DecryptSecret(b64PlainText string) (string, error) {
decoded, err := base64.StdEncoding.DecodeString(b64PlainText)
if err != nil {
return "", errors.New("could not decode base64 string")
}
out, err := KMS.Decrypt(&kms.DecryptInput{
CiphertextBlob: decoded,
EncryptionContext: map[string]*string{
`account`: aws.String(AwsAccount),
`application`: aws.String(Application),
},
})
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(out.Plaintext), nil
}