-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
155 lines (125 loc) · 4.32 KB
/
util.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package envcrypt // github.com/devries/envcrypt
import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
cloudkms "cloud.google.com/go/kms/apiv1"
// kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
"cloud.google.com/go/kms/apiv1/kmspb"
)
// EncodedMessage is a structure which containes an encrypted key as well as the
// encrypted ciphertext. It can be serialized to JSON.
type EncodedMessage struct {
EncryptedKey []byte `json:"encrypted_key,omitempty"`
Ciphertext []byte `json:"ciphertext,omitempty"`
}
// EnvelopeKey contains both an unencrypted and encrypted version of the encryption
// key for a message.
type EnvelopeKey struct {
PlainKey []byte
EncryptedKey []byte
}
func generateKeyAndEncryptedKey(ctx context.Context, keyspec string) (*EnvelopeKey, error) {
newkey := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, newkey); err != nil {
return nil, fmt.Errorf("unable to generate random numbers: %v", err)
}
client, err := cloudkms.NewKeyManagementClient(ctx)
if err != nil {
return nil, fmt.Errorf("unable to create KMS client: %v", err)
}
encreq := &kmspb.EncryptRequest{
Name: keyspec,
Plaintext: newkey,
}
resp, err := client.Encrypt(ctx, encreq)
if err != nil {
return nil, fmt.Errorf("unable to encrypt key: %v", err)
}
eKey := EnvelopeKey{
PlainKey: newkey,
EncryptedKey: resp.Ciphertext,
}
return &eKey, nil
}
func decryptKey(ctx context.Context, keyspec string, encKey []byte) ([]byte, error) {
client, err := cloudkms.NewKeyManagementClient(ctx)
if err != nil {
return nil, fmt.Errorf("unable to create KMS client: %v", err)
}
decreq := &kmspb.DecryptRequest{
Name: keyspec,
Ciphertext: encKey,
}
resp, err := client.Decrypt(ctx, decreq)
if err != nil {
return nil, fmt.Errorf("unable to decrypt key: %v", err)
}
return resp.Plaintext, nil
}
// EncryptMessage encrypts the data from the message Reader using a random encryption
// key, and then encrypts that key using the GCP CloudKMS key represented by keyspec.
// keyspec should be in the format project/{project_id}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}.
// The function returns an EncodedMessage and an error if there is an error.
func EncryptMessage(ctx context.Context, keyspec string, message io.Reader) (*EncodedMessage, error) {
key, err := generateKeyAndEncryptedKey(ctx, keyspec)
if err != nil {
return nil, fmt.Errorf("unable to generate key: %v", err)
}
block, err := aes.NewCipher(key.PlainKey)
if err != nil {
return nil, fmt.Errorf("unable to create cipher: %v", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("unable to create GCM cipher: %v", err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("unable to generate nonce: %v", err)
}
plaintext, err := io.ReadAll(message)
if err != nil {
return nil, fmt.Errorf("unable to read message: %v", err)
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
cryptoMessage := EncodedMessage{
EncryptedKey: key.EncryptedKey,
Ciphertext: ciphertext,
}
return &cryptoMessage, nil
}
// DecryptMessage takes a Cloud KMS keyspec, a pointer to an EncodedMessage, and
// writes the decrypted message to the Writer w, returning an error if any.
// keyspec is formated as project/{project_id}/locations/{location}/keyRings/{keyring}/cryptoKeys/{key}.
func DecryptMessage(ctx context.Context, keyspec string, encMessage *EncodedMessage, w io.Writer) error {
key, err := decryptKey(ctx, keyspec, encMessage.EncryptedKey)
if err != nil {
return fmt.Errorf("unable to decrypt key: %v", err)
}
block, err := aes.NewCipher(key)
if err != nil {
return fmt.Errorf("unable to create cipher: %v", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return fmt.Errorf("unable to create GCM cipher: %v", err)
}
if len(encMessage.Ciphertext) < gcm.NonceSize() {
return errors.New("ciphertext is too short")
}
nonce := encMessage.Ciphertext[:gcm.NonceSize()]
ciphertext := encMessage.Ciphertext[gcm.NonceSize():]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return fmt.Errorf("unable to read from cipher: %v", err)
}
if _, err := w.Write(plaintext); err != nil {
return fmt.Errorf("unable to write to writer: %v", err)
}
return nil
}