-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathejsonkms.go
More file actions
87 lines (70 loc) · 1.88 KB
/
ejsonkms.go
File metadata and controls
87 lines (70 loc) · 1.88 KB
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 (
"bytes"
"encoding/json"
"errors"
"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) {
data, err := os.ReadFile(ejsonFilePath)
if err != nil {
return nil, err
}
privateKeyEnc, err := extractPrivateKeyEnc(data)
if err != nil {
return nil, err
}
kmsDecryptedPrivateKey, err := decryptPrivateKeyWithKMS(privateKeyEnc, awsRegion)
if err != nil {
return nil, err
}
var output bytes.Buffer
if err := ejson.Decrypt(bytes.NewReader(data), &output, "", kmsDecryptedPrivateKey); err != nil {
return nil, err
}
return output.Bytes(), nil
}
func extractPrivateKeyEnc(data []byte) (string, error) {
var ejsonKmsKeys EjsonKmsKeys
if err := json.Unmarshal(data, &ejsonKmsKeys); err != nil {
return "", err
}
if len(ejsonKmsKeys.PrivateKeyEnc) == 0 {
return "", errors.New("missing _private_key_enc field")
}
return ejsonKmsKeys.PrivateKeyEnc, nil
}
// findPrivateKeyEnc reads a file and extracts the private key
func findPrivateKeyEnc(ejsonFilePath string) (string, error) {
data, err := os.ReadFile(ejsonFilePath)
if err != nil {
return "", err
}
return extractPrivateKeyEnc(data)
}