-
Notifications
You must be signed in to change notification settings - Fork 3
/
kms.go
52 lines (44 loc) · 1.41 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
package ejsonkms
import (
"encoding/base64"
"fmt"
"os"
"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"
)
func decryptPrivateKeyWithKMS(privateKeyEnc, awsRegion string) (key string, err error) {
kmsSvc := newKmsClient(awsRegion)
encryptedValue, err := base64.StdEncoding.DecodeString(privateKeyEnc)
params := &kms.DecryptInput{
CiphertextBlob: []byte(encryptedValue),
}
resp, err := kmsSvc.Decrypt(params)
if err != nil {
return "", fmt.Errorf("unable to decrypt parameter: %v", err)
}
return string(resp.Plaintext), nil
}
func encryptPrivateKeyWithKMS(privateKey, kmsKeyID, awsRegion string) (key string, err error) {
kmsSvc := newKmsClient(awsRegion)
params := &kms.EncryptInput{
KeyId: &kmsKeyID,
Plaintext: []byte(privateKey),
}
resp, err := kmsSvc.Encrypt(params)
if err != nil {
return "", fmt.Errorf("unable to encrypt parameter: %v", err)
}
encodedPrivKey := base64.StdEncoding.EncodeToString(resp.CiphertextBlob)
return encodedPrivKey, nil
}
func newKmsClient(awsRegion string) kmsiface.KMSAPI {
awsSession := session.Must(session.NewSession())
awsSession.Config.WithRegion(awsRegion)
fakeKmsEndpoint := os.Getenv("FAKE_AWSKMS_URL")
if len(fakeKmsEndpoint) != 0 {
return kms.New(awsSession, aws.NewConfig().WithEndpoint(fakeKmsEndpoint))
}
return kms.New(awsSession)
}