forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt_util.go
306 lines (275 loc) · 7.54 KB
/
encrypt_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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright (c) 2021-2022 Snowflake Computing Inc. All rights reserved.
package gosnowflake
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
)
type snowflakeFileEncryption struct {
QueryStageMasterKey string `json:"queryStageMasterKey,omitempty"`
QueryID string `json:"queryId,omitempty"`
SMKID int64 `json:"smkId,omitempty"`
}
// PUT requests return a single encryptionMaterial object whereas GET requests
// return a slice (array) of encryptionMaterial objects, both under the field
// 'encryptionMaterial'
type encryptionWrapper struct {
snowflakeFileEncryption
EncryptionMaterials []snowflakeFileEncryption
}
// override default behavior for wrapper
func (ew *encryptionWrapper) UnmarshalJSON(data []byte) error {
// if GET, unmarshal slice of encryptionMaterial
if err := json.Unmarshal(data, &ew.EncryptionMaterials); err == nil {
return err
}
// else (if PUT), unmarshal the encryptionMaterial itself
return json.Unmarshal(data, &ew.snowflakeFileEncryption)
}
type encryptMetadata struct {
key string
iv string
matdesc string
}
// encryptStream encrypts a stream buffer using AES128 block cipher in CBC mode
// with PKCS5 padding
func encryptStream(
sfe *snowflakeFileEncryption,
src io.Reader,
out io.Writer,
chunkSize int) (*encryptMetadata, error) {
if chunkSize == 0 {
chunkSize = aes.BlockSize * 4 * 1024
}
decodedKey, err := base64.StdEncoding.DecodeString(sfe.QueryStageMasterKey)
if err != nil {
return nil, err
}
keySize := len(decodedKey)
fileKey := getSecureRandom(keySize)
block, err := aes.NewCipher(fileKey)
if err != nil {
return nil, err
}
ivData := getSecureRandom(block.BlockSize())
mode := cipher.NewCBCEncrypter(block, ivData)
cipherText := make([]byte, chunkSize)
chunk := make([]byte, chunkSize)
// encrypt file with CBC
for {
n, err := src.Read(chunk)
if n == 0 || err != nil {
break
} else if n%aes.BlockSize != 0 || n != chunkSize {
chunk = padBytesLength(chunk[:n], aes.BlockSize)
}
mode.CryptBlocks(cipherText, chunk)
out.Write(cipherText[:len(chunk)])
}
if err != nil {
return nil, err
}
// encrypt key with ECB
fileKey = padBytesLength(fileKey, block.BlockSize())
encryptedFileKey := make([]byte, len(fileKey))
if err = encryptECB(encryptedFileKey, fileKey, decodedKey); err != nil {
return nil, err
}
matDesc := materialDescriptor{
strconv.Itoa(int(sfe.SMKID)),
sfe.QueryID,
strconv.Itoa(keySize * 8),
}
matDescUnicode, err := matdescToUnicode(matDesc)
if err != nil {
return nil, err
}
return &encryptMetadata{
base64.StdEncoding.EncodeToString(encryptedFileKey),
base64.StdEncoding.EncodeToString(ivData),
matDescUnicode,
}, nil
}
func encryptECB(encrypted []byte, fileKey []byte, decodedKey []byte) error {
block, err := aes.NewCipher(decodedKey)
if err != nil {
return err
}
if len(fileKey)%block.BlockSize() != 0 {
return fmt.Errorf("input not full of blocks")
}
if len(encrypted) < len(fileKey) {
return fmt.Errorf("output length is smaller than input length")
}
for len(fileKey) > 0 {
block.Encrypt(encrypted, fileKey[:block.BlockSize()])
encrypted = encrypted[block.BlockSize():]
fileKey = fileKey[block.BlockSize():]
}
return nil
}
func decryptECB(decrypted []byte, keyBytes []byte, decodedKey []byte) error {
block, err := aes.NewCipher(decodedKey)
if err != nil {
return err
}
if len(keyBytes)%block.BlockSize() != 0 {
return fmt.Errorf("input not full of blocks")
}
if len(decrypted) < len(keyBytes) {
return fmt.Errorf("output length is smaller than input length")
}
for len(keyBytes) > 0 {
block.Decrypt(decrypted, keyBytes[:block.BlockSize()])
keyBytes = keyBytes[block.BlockSize():]
decrypted = decrypted[block.BlockSize():]
}
return nil
}
func encryptFile(
sfe *snowflakeFileEncryption,
filename string,
chunkSize int,
tmpDir string) (
*encryptMetadata, string, error) {
if chunkSize == 0 {
chunkSize = aes.BlockSize * 4 * 1024
}
tmpOutputFile, err := ioutil.TempFile(tmpDir, baseName(filename)+"#")
if err != nil {
return nil, "", err
}
infile, err := os.OpenFile(filename, os.O_CREATE|os.O_RDONLY, os.ModePerm)
if err != nil {
return nil, "", err
}
meta, err := encryptStream(sfe, infile, tmpOutputFile, chunkSize)
if err != nil {
return nil, "", err
}
return meta, tmpOutputFile.Name(), nil
}
func decryptFile(
metadata *encryptMetadata,
sfe *snowflakeFileEncryption,
filename string,
chunkSize int,
tmpDir string) (
string, error) {
if chunkSize == 0 {
chunkSize = aes.BlockSize * 4 * 1024
}
decodedKey, err := base64.StdEncoding.DecodeString(sfe.QueryStageMasterKey)
if err != nil {
return "", err
}
keyBytes, err := base64.StdEncoding.DecodeString(metadata.key) // encrypted file key
if err != nil {
return "", err
}
ivBytes, err := base64.StdEncoding.DecodeString(metadata.iv)
if err != nil {
return "", err
}
// decrypt file key
decryptedKey := make([]byte, len(keyBytes))
if err = decryptECB(decryptedKey, keyBytes, decodedKey); err != nil {
return "", err
}
decryptedKey = paddingTrim(decryptedKey)
// decrypt file
block, err := aes.NewCipher(decryptedKey)
if err != nil {
return "", err
}
mode := cipher.NewCBCDecrypter(block, ivBytes)
tmpOutputFile, err := ioutil.TempFile(tmpDir, baseName(filename)+"#")
if err != nil {
return "", err
}
defer tmpOutputFile.Close()
infile, err := os.OpenFile(filename, os.O_RDONLY, os.ModePerm)
if err != nil {
return "", err
}
defer infile.Close()
var totalFileSize int
var prevChunk []byte
for {
chunk := make([]byte, chunkSize)
n, err := infile.Read(chunk)
if n == 0 || err != nil {
break
}
totalFileSize += n
chunk = chunk[:n]
mode.CryptBlocks(chunk, chunk)
tmpOutputFile.Write(chunk)
prevChunk = chunk
}
if err != nil {
return "", err
}
if prevChunk != nil {
totalFileSize -= paddingOffset(prevChunk)
}
tmpOutputFile.Truncate(int64(totalFileSize))
return tmpOutputFile.Name(), nil
}
type materialDescriptor struct {
SmkID string `json:"smkId"`
QueryID string `json:"queryId"`
KeySize string `json:"keySize"`
}
func matdescToUnicode(matdesc materialDescriptor) (string, error) {
s, err := json.Marshal(&matdesc)
if err != nil {
return "", err
}
return string(s), nil
}
func getSecureRandom(byteLength int) []byte {
token := make([]byte, byteLength)
rand.Read(token)
return token
}
func padBytesLength(src []byte, blockSize int) []byte {
padLength := blockSize - len(src)%blockSize
padText := bytes.Repeat([]byte{byte(padLength)}, padLength)
return append(src, padText...)
}
func paddingTrim(src []byte) []byte {
unpadding := src[len(src)-1]
return src[:len(src)-int(unpadding)]
}
func paddingOffset(src []byte) int {
length := len(src)
return int(src[length-1])
}
type contentKey struct {
KeyID string `json:"KeyId,omitempty"`
EncryptionKey string `json:"EncryptedKey,omitempty"`
Algorithm string `json:"Algorithm,omitempty"`
}
type encryptionAgent struct {
Protocol string `json:"Protocol,omitempty"`
EncryptionAlgorithm string `json:"EncryptionAlgorithm,omitempty"`
}
type keyMetadata struct {
EncryptionLibrary string `json:"EncryptionLibrary,omitempty"`
}
type encryptionData struct {
EncryptionMode string `json:"EncryptionMode,omitempty"`
WrappedContentKey contentKey `json:"WrappedContentKey,omitempty"`
EncryptionAgent encryptionAgent `json:"EncryptionAgent,omitempty"`
ContentEncryptionIV string `json:"ContentEncryptionIV,omitempty"`
KeyWrappingMetadata keyMetadata `json:"KeyWrappingMetadata,omitempty"`
}