-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcrypto.go
More file actions
560 lines (438 loc) · 12.7 KB
/
crypto.go
File metadata and controls
560 lines (438 loc) · 12.7 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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
// Cryptographic functions
package varuh
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha512"
"errors"
"fmt"
"golang.org/x/crypto/argon2"
chacha "golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/pbkdf2"
"io"
"math/big"
"math/rand"
"os"
"time"
"unsafe"
crand "crypto/rand"
)
const KEY_SIZE = 32
const SALT_SIZE = 128
const KEY_N_ITER = 120000
const HMAC_SHA512_SIZE = 64
const MAGIC_HEADER = 0xcafebabe
// Generate random bytes of the given length
func GenerateRandomBytes(size int) (error, []byte) {
var data []byte
data = make([]byte, size)
_, err := crand.Read(data)
if err != nil {
fmt.Printf("Error generating random data - \"%s\"\n", err.Error())
return err, data
}
return nil, data
}
// Generate a key from the given passphrase and (optional) salt
// If 2nd argument is nil, salt will be generated. Uses argon2
func GenerateKeyArgon2(passPhrase string, oldSalt *[]byte) (error, []byte, []byte) {
var salt []byte
var key []byte
var err error
if oldSalt == nil {
err, salt = GenerateRandomBytes(SALT_SIZE)
} else {
if len(*oldSalt) != SALT_SIZE {
return errors.New("invalid salt length"), key, salt
}
salt = *oldSalt
}
if err != nil {
return err, key, salt
}
if len(salt) == 0 {
return errors.New("invalid salt"), key, salt
}
// key = argon2.IDKey([]byte(passPhrase), salt, 1, 64*1024, 4, KEY_SIZE)
key = argon2.Key([]byte(passPhrase), salt, 3, 32*1024, 4, KEY_SIZE)
return nil, key, salt
}
// Generate a key from the given passphrase and (optional) salt
// If 2nd argument is nil, salt will be generated. Uses pbkdf2
func GenerateKey(passPhrase string, oldSalt *[]byte) (error, []byte, []byte) {
var salt []byte
var key []byte
var err error
if oldSalt == nil {
err, salt = GenerateRandomBytes(SALT_SIZE)
} else {
if len(*oldSalt) != SALT_SIZE {
return errors.New("invalid salt length"), key, salt
}
salt = *oldSalt
}
if err != nil {
return err, key, salt
}
if len(salt) == 0 {
return errors.New("invalid salt"), key, salt
}
key = pbkdf2.Key([]byte(passPhrase), salt, KEY_N_ITER, KEY_SIZE, sha512.New)
return nil, key, salt
}
// Return if file is encrypted by looking at the magic header
func IsFileEncrypted(encDbPath string) (error, bool) {
var magicBytes string
var header []byte
var err error
var fh *os.File
fh, err = os.Open(encDbPath)
if err != nil {
return fmt.Errorf("Error - Can't read database -\"%s\"\n", err.Error()), false
}
defer fh.Close()
// Read the header
magicBytes = fmt.Sprintf("%x", MAGIC_HEADER)
header = make([]byte, unsafe.Sizeof(MAGIC_HEADER))
_, err = io.ReadFull(fh, header[:])
if err != nil {
if err == io.EOF {
return fmt.Errorf("Not an encrypted database - file is empty"), false
}
return fmt.Errorf("Error - Can't read file header -\"%s\"\n", err.Error()), false
}
if string(header) != magicBytes {
return fmt.Errorf("Not an encrypted database - invalid magic number"), false
}
return nil, true
}
// Encrypt the database path using AES
func EncryptFileAES(dbPath string, password string) error {
var err error
var key []byte
var salt []byte
var nonce []byte
var plainText []byte
var cipherText []byte
var magicBytes []byte
var encText []byte
var encDbPath string
var hmacHash []byte
plainText, err = os.ReadFile(dbPath)
if err != nil {
fmt.Printf("Error - Can't read database -\"%s\"\n", err)
return err
}
err, key, salt = GenerateKeyArgon2(password, nil)
if err != nil {
fmt.Printf("Error - Key derivation failed -\"%s\"\n", err)
return err
}
// fmt.Printf("\nsalt: %x\n", salt)
// fmt.Printf("key: %x\n", key)
cipherBlock, err := aes.NewCipher(key)
if err != nil {
fmt.Printf("Error - Cipher block creation failed - \"%s\"\n", err)
return err
}
aesGCM, err := cipher.NewGCM(cipherBlock)
if err != nil {
fmt.Printf("Error - AES GCM creation failed - \"%s\"\n", err)
return err
}
nonceSize := aesGCM.NonceSize()
// fmt.Printf("%d\n", nonceSize)
err, nonce = GenerateRandomBytes(nonceSize)
if err != nil {
fmt.Printf("Error - Nonce generation failed -\"%s\"\n", err)
return err
}
// fmt.Printf("nonce: %x\n", nonce)
magicBytes = []byte(fmt.Sprintf("%x", MAGIC_HEADER))
cipherText = aesGCM.Seal(nonce, nonce, plainText, nil)
// Calculate hmac signature and write it
hCipher := hmac.New(sha512.New, key)
hCipher.Write(cipherText)
hmacHash = hCipher.Sum(nil)
encText = append(magicBytes, salt...)
encText = append(encText, hmacHash...)
encText = append(encText, cipherText...)
encDbPath = dbPath + ".varuh"
err = os.WriteFile(encDbPath, encText, 0600)
if err == nil {
err = os.WriteFile(dbPath, encText, 0600)
if err == nil {
// Remove backup
os.Remove(encDbPath)
} else {
fmt.Printf("Error writing encrypted database - \"%s\"\n", err.Error())
}
}
// fmt.Printf("%x\n", cipherText)
return err
}
// Decrypt an already encrypted database file using given password using AES
func DecryptFileAES(encDbPath string, password string) error {
var encText []byte
var cipherText []byte
var plainText []byte
var key []byte
var salt []byte
var nonce []byte
var hmacHash []byte
var hmacSig []byte
var origFile string
var err error
encText, err = os.ReadFile(encDbPath)
if err != nil {
fmt.Printf("Error - Can't read database -\"%s\"\n", err)
return err
}
encText = encText[unsafe.Sizeof(MAGIC_HEADER):]
// Read the old salt
salt, encText = encText[:SALT_SIZE], encText[SALT_SIZE:]
// Read the hmac hash checksum
hmacHash, encText = encText[:HMAC_SHA512_SIZE], encText[HMAC_SHA512_SIZE:]
err, key, _ = GenerateKeyArgon2(password, &salt)
if err != nil {
fmt.Printf("Error - Key derivation failed -\"%s\"\n", err)
return err
}
// verify the hmac
// Calculate hmac signature and write it
hCipher := hmac.New(sha512.New, key)
hCipher.Write(encText)
hmacSig = hCipher.Sum(nil)
// Compare
if !hmac.Equal(hmacSig, hmacHash) {
fmt.Println("Invalid password or tampered data. Aborted")
return errors.New("signature check failed")
}
// fmt.Printf("\nsalt: %x\n", salt)
// fmt.Printf("key: %x\n", key)
cipherBlock, err := aes.NewCipher(key)
if err != nil {
fmt.Printf("Error - Cipher block creation failed - \"%s\"\n", err)
return err
}
aesGCM, err := cipher.NewGCM(cipherBlock)
if err != nil {
fmt.Printf("Error - AES GCM creation failed - \"%s\"\n", err)
return err
}
nonceSize := aesGCM.NonceSize()
nonce, cipherText = encText[:nonceSize], encText[nonceSize:]
// fmt.Printf("nonce: %x\n", nonce)
plainText, err = aesGCM.Open(nil, nonce, cipherText, nil)
if err != nil {
fmt.Printf("Error - Decryption failed - \"%s\"\n", err)
return err
}
err, origFile = RewriteFile(encDbPath, plainText, 0600)
if err != nil {
fmt.Printf("Error writing decrypted data to %s - \"%s\"\n", origFile, err.Error())
}
// fmt.Printf("%s\n", string(plainText))
return err
}
// Encrypt a file using XChaCha20-Poly1305 cipher
func EncryptFileXChachaPoly(dbPath string, password string) error {
var err error
var key []byte
var nonce []byte
var salt []byte
var plainText []byte
var cipherText []byte
var magicBytes []byte
var encText []byte
var encDbPath string
var hmacHash []byte
plainText, err = os.ReadFile(dbPath)
if err != nil {
fmt.Printf("Error - Can't read database -\"%s\"\n", err)
return err
}
err, key, salt = GenerateKeyArgon2(password, nil)
if err != nil {
fmt.Printf("Error - Key derivation failed -\"%s\"\n", err)
return err
}
aead, err := chacha.NewX(key)
if err != nil {
fmt.Printf("Error - AEAD creation failed - \"%s\"\n", err)
return err
}
nonce = make([]byte, aead.NonceSize(), aead.NonceSize()+len(plainText)+aead.Overhead())
if _, err = crand.Read(nonce); err != nil {
fmt.Printf("Error - Nonce generation failed -\"%s\"\n", err)
return err
}
magicBytes = []byte(fmt.Sprintf("%x", MAGIC_HEADER))
cipherText = aead.Seal(nonce, nonce, plainText, nil)
// Calculate hmac signature and write it
hCipher := hmac.New(sha512.New, key)
hCipher.Write(cipherText)
hmacHash = hCipher.Sum(nil)
// No need for salt in chacha
encText = append(magicBytes, salt...)
encText = append(encText, hmacHash...)
encText = append(encText, cipherText...)
encDbPath = dbPath + ".varuh"
err = os.WriteFile(encDbPath, encText, 0600)
if err == nil {
err = os.WriteFile(dbPath, encText, 0600)
if err == nil {
// Remove backup
os.Remove(encDbPath)
} else {
fmt.Printf("Error writing encrypted database - \"%s\"\n", err.Error())
}
}
// fmt.Printf("%x\n", cipherText)
return err
}
// Decrypt an already encrypted database file using given password using XChaCha20-Poly1305
func DecryptFileXChachaPoly(encDbPath string, password string) error {
var encText []byte
var cipherText []byte
var plainText []byte
var salt []byte
var key []byte
var nonce []byte
var hmacHash []byte
var hmacSig []byte
var origFile string
var err error
encText, err = os.ReadFile(encDbPath)
if err != nil {
fmt.Printf("Error - Can't read database -\"%s\"\n", err)
return err
}
encText = encText[unsafe.Sizeof(MAGIC_HEADER):]
// Read the old salt
salt, encText = encText[:SALT_SIZE], encText[SALT_SIZE:]
// Read the hmac hash checksum
hmacHash, encText = encText[:HMAC_SHA512_SIZE], encText[HMAC_SHA512_SIZE:]
err, key, _ = GenerateKeyArgon2(password, &salt)
if err != nil {
fmt.Printf("Error - Key derivation failed -\"%s\"\n", err)
return err
}
// verify the hmac
// Calculate hmac signature and write it
hCipher := hmac.New(sha512.New, key)
hCipher.Write(encText)
hmacSig = hCipher.Sum(nil)
// Compare
if !hmac.Equal(hmacSig, hmacHash) {
fmt.Println("Invalid password or tampered data. Aborted")
return errors.New("signature check failed")
}
// fmt.Printf("\nsalt: %x\n", salt)
// fmt.Printf("key: %x\n", key)
aead, err := chacha.NewX(key)
if err != nil {
fmt.Printf("Error - AEAD creation failed - \"%s\"\n", err)
return err
}
nonceSize := aead.NonceSize()
nonce, cipherText = encText[:nonceSize], encText[nonceSize:]
// fmt.Printf("nonce: %x\n", nonce)
plainText, err = aead.Open(nil, nonce, cipherText, nil)
if err != nil {
fmt.Printf("Error - Decryption failed - \"%s\"\n", err)
return err
}
// err = os.WriteFile("test.sqlite3", oplainText, 0600)
err, origFile = RewriteFile(encDbPath, plainText, 0600)
if err != nil {
fmt.Printf("Error writing decrypted data to %s - \"%s\"\n", origFile, err.Error())
}
// fmt.Printf("%s\n", string(plainText))
return err
}
// Generate a random password - for adding listings
func GeneratePassword(length int) (error, string) {
var data []byte
const source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789=+_()$#@!~:/%"
data = make([]byte, length)
for i := 0; i < length; i++ {
num, err := crand.Int(crand.Reader, big.NewInt(int64(len(source))))
if err != nil {
return err, ""
}
data[i] = source[num.Int64()]
}
return nil, string(data)
}
// Generate a "strong" password
// A strong password is defined as,
// A mix of upper and lower case alphabets
// at least one number [0-9]
// at least one upper case alphabet [A-Z]
// at least one punctuation character
// at least length 12
func GenerateStrongPassword() (error, string) {
var data []byte
var length int
const sourceAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const sourceLargeAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const sourceNum = "0123456789"
const sourcePunct = "=+_()$#@!~:/%"
const source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789=+_()$#@!~:/%"
// Generate in range 12 - 16
rand.Seed(time.Now().UnixNano())
length = rand.Intn(4) + 12
data = make([]byte, length)
var lengthAlpha int
var i, j, k, l int
// Alpha chars is at least length 3-5
lengthAlpha = rand.Intn(2) + 3
for i = 0; i < lengthAlpha; i++ {
num, err := crand.Int(crand.Reader, big.NewInt(int64(len(sourceAlpha))))
if err != nil {
return err, ""
}
data[i] = sourceAlpha[num.Int64()]
}
// Add in numbers 1 or 2
var lengthNum int
lengthNum = rand.Intn(2) + 1
for j = i; j < i+lengthNum; j++ {
num, err := crand.Int(crand.Reader, big.NewInt(int64(len(sourceNum))))
if err != nil {
return err, ""
}
data[j] = sourceNum[num.Int64()]
}
// Add in punctuations 1 or 2
var lengthPunc int
lengthPunc = rand.Intn(2) + 1
for k = j; k < j+lengthPunc; k++ {
num, err := crand.Int(crand.Reader, big.NewInt(int64(len(sourcePunct))))
if err != nil {
return err, ""
}
data[k] = sourcePunct[num.Int64()]
}
// Fill in the rest
var lengthRem int
lengthRem = length - k
if lengthRem > 0 {
for l = k; l < k+lengthRem; l++ {
num, err := crand.Int(crand.Reader, big.NewInt(int64(len(source))))
if err != nil {
return err, ""
}
data[l] = source[num.Int64()]
}
}
// Shuffle a few times
for i = 0; i < 5; i++ {
rand.Shuffle(len(data), func(i, j int) {
data[i], data[j] = data[j], data[i]
})
}
return nil, string(data)
}