-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes_gcm_chunks.go
469 lines (430 loc) · 14.8 KB
/
aes_gcm_chunks.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package cryptography
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"errors"
"github.com/jaeha-choi/Proj_Coconut_Utility/common"
"github.com/jaeha-choi/Proj_Coconut_Utility/log"
"github.com/jaeha-choi/Proj_Coconut_Utility/util"
"io"
"io/ioutil"
"math"
"os"
"path/filepath"
)
const (
// ChunkSize is a size of each file chunks in bytes.
// Should be less than max value of uint32 (4294967295)
// since the util package use unsigned 4 bytes to represent the data size.
ChunkSize = 16777216 // 2^24 bytes, about 16.7 MB
IvSize = 12
SymKeySize = 32
// MaxFileSize indicates theoretical limit for the file size. Because chunk number are
// indicated with uint16, MaxFileSize depends on ChunkSize. However, actual file limit
// may depend on the IV, file system, OS, etc.
//MaxFileSize = ChunkSize * 65535
//gcmOverhead = 16
)
// ChunkIncorrectOrder occurs when encrypted file chunks are received in incorrect order.
var ChunkIncorrectOrder = errors.New("encrypted chunk incorrect order")
// IncompleteFile occurs when written chunk size != total chunk size.
var IncompleteFile = errors.New("incomplete file")
// AesGcmChunk stores data for encrypting or decrypting chunks, but it cannot be both.
type AesGcmChunk struct {
key []byte
file *os.File
fileName string
readOffset uint64
readChunkNum uint16
writeOffset uint64
writeChunkNum uint16
fileSize uint64
chunkCount uint16
}
// EncryptSetup opens file, determine number of chunks, then return *AesGcmChunk
func EncryptSetup(fileN string) (ag *AesGcmChunk, err error) {
// Generate symmetric encryption key
symKey, err := genSymKey()
if err != nil {
log.Debug(err)
log.Error("Error while generating an AES key")
return nil, err
}
// Open src file for encryption
srcFile, err := os.Open(fileN)
if err != nil {
log.Debug(err)
log.Error("Error while opening a file")
return nil, err
}
// Get size of the src file
fileStat, err := os.Stat(fileN)
if err != nil {
log.Debug(err)
log.Error("Error while getting stats")
return nil, err
}
// Split path from file name so dst file can use this file name
_, fileName := filepath.Split(fileN)
// Get file size
fileSize := fileStat.Size()
// Get number of chunks
chunkNum := math.Ceil(float64(fileSize) / ChunkSize)
return &AesGcmChunk{
key: symKey,
file: srcFile,
fileName: fileName,
readOffset: 0,
readChunkNum: 0,
writeOffset: 0,
writeChunkNum: 0,
fileSize: uint64(fileSize),
chunkCount: uint16(chunkNum),
}, nil
}
// DecryptSetup creates temporary file, make directory if it doesn't exist then return *AesGcmChunk
func DecryptSetup() (ag *AesGcmChunk, err error) {
// Create directory if it doesn't exist
if err = os.MkdirAll(util.DownloadPath, os.ModePerm); err != nil {
log.Debug(err)
log.Error("Error while creating download directory")
return nil, err
}
// Create file for decrypted data
tmpFile, err := ioutil.TempFile(util.DownloadPath, ".tmp_decrypted_")
if err != nil {
log.Debug(err)
log.Error("Temp file could not be created")
return nil, err
}
return &AesGcmChunk{
key: nil,
file: tmpFile,
fileName: "",
readOffset: 0,
readChunkNum: 0,
writeOffset: 0,
writeChunkNum: 0,
fileSize: 0,
chunkCount: 0,
}, nil
}
// Encrypt encrypts file and write to writer and return error if raised.
// Receiver's public key is required for encrypting symmetric encryption key.
// Sender's private key is required for signing the encrypted key.
// err == nil indicates successful execution.
// TODO: Send error if previous operation was unsuccessful
func (ag *AesGcmChunk) Encrypt(writer io.Writer, receiverPubKey *rsa.PublicKey, senderPrivKey *rsa.PrivateKey) (err error) {
var command = common.File
// Encrypt and sign symmetric encryption key
dataEncrypted, dataSignature, err := EncryptSignMsg(ag.key, receiverPubKey, senderPrivKey)
if err != nil {
log.Debug(err)
log.Error("Error in EncryptSignMsg")
return err
}
// Send encrypted symmetric key
if _, err = util.WriteMessage(writer, dataEncrypted, nil, command); err != nil {
log.Debug(err)
log.Error("Error in WriteBytes while sending dataEncrypted")
return err
}
// Send encrypted symmetric key signature
if _, err = util.WriteMessage(writer, dataSignature, nil, command); err != nil {
log.Debug(err)
log.Error("Error in WriteBytes while sending dataSignature")
return err
}
// Encrypt chunkCount + file name
encryptedFileName, fileNameIv, err := ag.encryptBytes(append(util.Uint16ToByte(ag.chunkCount), []byte(ag.fileName)...))
if err != nil {
log.Debug(err)
log.Error("Error in encryptBytes while encrypting file name")
return err
}
// Send IV (Nonce)
if _, err = util.WriteMessage(writer, fileNameIv, nil, command); err != nil {
log.Debug(err)
log.Error("Error in WriteBytes while writing fileNameIv")
return err
}
// Send encrypted file name
if _, err = util.WriteMessage(writer, encryptedFileName, nil, command); err != nil {
log.Debug(err)
log.Error("Error in WriteBytes while writing encrypted file name")
return err
}
// Send encrypted file
var encryptedFileChunk, iv []byte
// Loop until every byte is sent
// ag.readOffset and ag.readChunkNum are updated in encryptChunk
for ag.readOffset < ag.fileSize {
if ag.readOffset+ChunkSize >= ag.fileSize {
// Send last chunk
encryptedFileChunk, iv, err = ag.encryptChunk(ag.fileSize - ag.readOffset)
} else {
// Send chunk
encryptedFileChunk, iv, err = ag.encryptChunk(ChunkSize)
}
if err != nil {
log.Debug(err)
log.Error("Error in encryptChunk. Read Offset: ", int(ag.readOffset))
return err
}
// Send IV in plain text
if _, err = util.WriteMessage(writer, iv, nil, command); err != nil {
log.Debug(err)
log.Error("Error in WriteBytes while sending iv")
return err
}
// Send encrypted file chunk + current chunk number (first two bytes)
if _, err = util.WriteMessage(writer, encryptedFileChunk, nil, command); err != nil {
log.Debug(err)
log.Error("Error in WriteBytes while sending encryptedFileChunk")
return err
}
}
// Close input file when done reading
if err := ag.file.Close(); err != nil {
log.Debug(err)
return err
}
return nil
}
// encryptChunk encrypts portion of the file and return it as []byte with current chunk number
// appended in the beginning (first two bytes). IV is also returned in plain text.
// err == nil indicates successful execution.
func (ag *AesGcmChunk) encryptChunk(chunkSize uint64) (encryptedData []byte, iv []byte, err error) {
// Read chunk of file to encrypt
plain := make([]byte, int(chunkSize))
//plain := make([]byte, int(chunkSize)-gcmOverhead-len(currChunkNum))
if _, err := io.ReadFull(ag.file, plain); err != nil {
log.Debug(err)
log.Error("Error while reading src file")
return nil, nil, err
}
// Get current chunk number
currChunkNum := util.Uint16ToByte(ag.readChunkNum)
// Plain data is combined with current chunk number to be sent
plain = append(currChunkNum, plain...)
// Encrypt chunk of file and return encrypted output, IV, and error, if any.
if encryptedData, iv, err = ag.encryptBytes(plain); err != nil {
log.Debug(err)
log.Error("Error in encryptBytes")
return nil, nil, err
}
// Update variables for loop in Encrypt
ag.readChunkNum += 1
ag.readOffset += uint64(len(plain) - len(currChunkNum))
return encryptedData, iv, err
}
// encryptBytes encrypts plain and return encrypted data, IV that was used, and error, if any.
// err == nil indicates successful execution.
func (ag *AesGcmChunk) encryptBytes(plain []byte) (encryptedData []byte, iv []byte, err error) {
block, err := aes.NewCipher(ag.key)
if err != nil {
log.Debug(err)
log.Error("Error while creating new cipher block")
return nil, nil, err
}
// Generate random IV.
// To save some bandwidth, some portion of the IV can be static (e.g. 32 bits)
// while the rest (e.g. 64 bits) remains dynamic.
iv = make([]byte, IvSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
log.Debug(err)
log.Error("Error while creating iv")
return nil, nil, err
}
aesGcm, err := cipher.NewGCM(block)
if err != nil {
log.Debug(err)
log.Error("Error in NewGCM")
return nil, iv, err
}
// Get encrypted data
encryptedData = aesGcm.Seal(nil, iv, plain, nil)
return encryptedData, iv, nil
}
// Decrypt reads encrypted data from reader and decrypts the file and return error, if raised.
// Sender's public key is required for verifying signature.
// Receiver's private key is required for decrypting symmetric encryption key.
// err == nil indicates successful execution.
func (ag *AesGcmChunk) Decrypt(chanMap chan *util.Message, senderPubKey *rsa.PublicKey, receiverPrivKey *rsa.PrivateKey) (err error) {
// Reads encrypted symmetric encryption key
dataEncrypted := <-chanMap
if dataEncrypted.ErrorCode != 0 {
log.Debug(err)
log.Error("Error in ReadBytes while getting dataEncrypted")
return common.ErrorCodes[dataEncrypted.ErrorCode]
}
// Reads signature for encrypted symmetric encryption key
dataSignature := <-chanMap
if dataSignature.ErrorCode != 0 {
log.Debug(err)
log.Error("Error in ReadBytes while getting dataEncrypted")
return common.ErrorCodes[dataSignature.ErrorCode]
}
// Verify and decrypts symmetric encryption key
ag.key, err = DecryptVerifyMsg(dataEncrypted.Data, dataSignature.Data, senderPubKey, receiverPrivKey)
if err != nil {
log.Debug(err)
log.Error("Error in DecryptVerifyMsg")
return err
}
// Get IV for decrypting file name
ivFileName := <-chanMap
if ivFileName.ErrorCode != 0 {
log.Debug(err)
log.Error("Error while reading iv for file name")
return common.ErrorCodes[ivFileName.ErrorCode]
}
// Get encrypted chunkCount + file name
encryptedFileName := <-chanMap
if encryptedFileName.ErrorCode != 0 {
log.Debug(err)
log.Error("Error while reading encrypted file name")
return common.ErrorCodes[encryptedFileName.ErrorCode]
}
// Decrypt chunkCount + file name with encrypted data and IV
decryptedFileName, err := ag.decryptBytes(encryptedFileName.Data, ivFileName.Data)
if err != nil {
log.Debug(err)
log.Error("Error while decrypting file name")
return err
}
// Total chunk count is appended to file name
ag.chunkCount = util.ByteToUint16(decryptedFileName[:2])
// Update file name
ag.fileName = string(decryptedFileName[2:])
// Receive file and decrypt
var encryptedFileChunk, iv *util.Message
// Loop until every chunk is received
// ag.writeOffset and ag.writeChunkNum are updated in decryptChunk
for ag.writeChunkNum < ag.chunkCount {
// Read IV in plain text
if iv = <-chanMap; iv.ErrorCode != 0 {
log.Debug(err)
log.Error("Error in ReadBytes while reading iv")
return common.ErrorCodes[iv.ErrorCode]
}
// Read encrypted file chunk + current chunk number (first two bytes)
if encryptedFileChunk = <-chanMap; encryptedFileChunk.ErrorCode != 0 {
log.Debug(err)
log.Error("Error in ReadBytes while reading encryptedFileChunk")
return common.ErrorCodes[encryptedFileChunk.ErrorCode]
}
// Decrypt file chunk + current chunk number (first two bytes)
decryptedFileChunk, _, err := ag.decryptChunk(encryptedFileChunk.Data, iv.Data)
if err != nil {
log.Debug(err)
log.Error("Error in decryptChunk")
return err
}
// Write decrypted data to temp file
if _, err = ag.file.Write(decryptedFileChunk); err != nil {
log.Debug(err)
log.Error("Error while writing decrypted file chunk to temp file")
return err
}
}
// Close output file when done writing
if err := ag.file.Close(); err != nil {
log.Debug(err)
// If rename was unsuccessful, remove temp file
if err := os.Remove(ag.file.Name()); err != nil {
log.Debug(err)
log.Error("Error while removing temp file. Temp file at: ", ag.file.Name())
return err
}
return err
}
// If file was fully processed, rename temp file to actual name
if ag.writeChunkNum == ag.chunkCount {
// Rename temporary file
if err := os.Rename(ag.file.Name(), filepath.Join(util.DownloadPath, ag.fileName)); err != nil {
log.Debug(err)
log.Debug("Tmp file name: ", ag.file.Name())
log.Debug("File name: ", ag.fileName)
log.Error("Error moving the temp file to download path")
// If rename was unsuccessful, remove temp file
if err := os.Remove(ag.file.Name()); err != nil {
log.Debug(err)
log.Error("Error while removing temp file. Temp file at: ", ag.file.Name())
return err
}
return err
}
} else {
log.Error("Not all chunks were received")
// If file was not fully processed, delete file
if err := os.Remove(ag.file.Name()); err != nil {
log.Debug(err)
log.Error("Error while removing temp file. Temp file at: ", ag.file.Name())
return err
}
return IncompleteFile
}
return nil
}
// decryptChunk decrypts encryptedData with IV and current chunk number.
// Decrypted data and current chunk number is returned with error, if any.
// err == nil indicates successful execution.
func (ag *AesGcmChunk) decryptChunk(encryptedData []byte, iv []byte) (decryptedData []byte, currChunkNum uint16, err error) {
// Decrypt data
decryptedData, err = ag.decryptBytes(encryptedData, iv)
if err != nil {
log.Debug(err)
log.Error("Error in decryptBytes")
return nil, 0, err
}
// Convert chunk number bytes to uint16 (first two bytes)
currChunkNum = util.ByteToUint16(decryptedData[:2])
decryptedFileChunk := decryptedData[2:]
// If chunk was received in incorrect order, raise error
if ag.writeChunkNum != currChunkNum {
log.Error("Encrypted chunk was received in an incorrect order")
return decryptedFileChunk, currChunkNum, ChunkIncorrectOrder
}
// Update variables for loop in Decrypt
ag.writeChunkNum += 1
ag.writeOffset += uint64(len(decryptedFileChunk))
return decryptedFileChunk, currChunkNum, nil
}
// decryptBytes decrypts encryptedData with IV. Decrypted data and error is returned, if any.
// err == nil indicates successful execution.
func (ag *AesGcmChunk) decryptBytes(encryptedData []byte, iv []byte) (decryptedData []byte, err error) {
block, err := aes.NewCipher(ag.key)
if err != nil {
log.Debug(err)
log.Error("Error while creating new cipher block")
return nil, err
}
aesGcm, err := cipher.NewGCM(block)
if err != nil {
log.Debug(err)
log.Error("Error in NewGCM")
return nil, err
}
// Decrypt the encryptedData
if decryptedData, err = aesGcm.Open(nil, iv, encryptedData, nil); err != nil {
log.Debug(err)
log.Error("Error in Open in decryptChunk")
return nil, err
}
return decryptedData, nil
}
// genSymKey generates random key for symmetric encryption
func genSymKey() (key []byte, err error) {
// Since we're using AES, generate 32 bytes key for AES256
key = make([]byte, SymKeySize)
// Create random key for symmetric encryption
if _, err := rand.Read(key); err != nil {
log.Debug(err)
log.Error("Error while generating symmetric encryption key")
return nil, err
}
return key, nil
}