-
Notifications
You must be signed in to change notification settings - Fork 3
/
ejsonkms.go
87 lines (70 loc) · 1.73 KB
/
ejsonkms.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package ejsonkms
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
"github.com/Shopify/ejson"
)
// EjsonKmsKeys - keys used in an EjsonKms file
type EjsonKmsKeys struct {
PublicKey string `json:"_public_key"`
PrivateKeyEnc string `json:"_private_key_enc"`
PrivateKey string
}
// Keygen generates keys and prepares an EJSON file with them
func Keygen(kmsKeyID, awsRegion string) (EjsonKmsKeys, error) {
var ejsonKmsKeys EjsonKmsKeys
pub, priv, err := ejson.GenerateKeypair()
if err != nil {
return ejsonKmsKeys, err
}
privKeyEnc, err := encryptPrivateKeyWithKMS(priv, kmsKeyID, awsRegion)
if err != nil {
return ejsonKmsKeys, err
}
ejsonKmsKeys = EjsonKmsKeys{
PublicKey: pub,
PrivateKeyEnc: privKeyEnc,
PrivateKey: priv,
}
return ejsonKmsKeys, nil
}
// Decrypt decrypts an EJSON file
func Decrypt(ejsonFilePath, awsRegion string) ([]byte, error) {
privateKeyEnc, err := findPrivateKeyEnc(ejsonFilePath)
if err != nil {
return nil, err
}
kmsDecryptedPrivateKey, err := decryptPrivateKeyWithKMS(privateKeyEnc, awsRegion)
if err != nil {
return nil, err
}
decrypted, err := ejson.DecryptFile(ejsonFilePath, "", kmsDecryptedPrivateKey)
if err != nil {
return nil, err
}
return decrypted, nil
}
func findPrivateKeyEnc(ejsonFilePath string) (key string, err error) {
var (
ejsonKmsKeys EjsonKmsKeys
)
file, err := os.Open(ejsonFilePath)
if err != nil {
return "", err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return "", err
}
err = json.Unmarshal(data, &ejsonKmsKeys)
if err != nil {
return "", err
}
if len(ejsonKmsKeys.PrivateKeyEnc) == 0 {
return "", errors.New("missing _private_key_enc field")
}
return ejsonKmsKeys.PrivateKeyEnc, nil
}