-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
executable file
·71 lines (57 loc) · 1.26 KB
/
crypto.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
package kvod
import (
"crypto/aes"
"crypto/cipher"
"crypto/sha1"
"golang.org/x/crypto/pbkdf2"
)
const (
keySize = 32
saltSize = 12
nonceSize = 12
iterations = 10000
)
type crypto struct {
key []byte
}
// InitCrypto inizialize the crypto struct using password and salt to generate the main key
func InitCrypto(password string, salt []byte) *crypto {
key := generateKey([]byte(password), salt)
return &crypto{key}
}
func (c *crypto) encrypt(data []byte) ([]byte, error) {
nonce, err := GenerateRandom(nonceSize)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(c.key)
if err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
encrypted := aesgcm.Seal(nonce, nonce, data, nil)
return encrypted, nil
}
func (c *crypto) decrypt(data []byte) ([]byte, error) {
nonce := data[:nonceSize]
cp, err := aes.NewCipher(c.key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(cp)
if err != nil {
return nil, err
}
out, err := gcm.Open(nil, nonce, data[nonceSize:], nil)
if err != nil {
return nil, err
}
return out, nil
}
func generateKey(passphrase []byte, salt []byte) []byte {
dk := pbkdf2.Key(passphrase, salt, iterations, keySize, sha1.New)
return dk
}