-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcrypt.go
52 lines (47 loc) · 991 Bytes
/
crypt.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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"golang.org/x/crypto/scrypt"
)
func deriveKey(password string, salt []byte) (key, salt2 []byte, err error) {
if salt == nil {
salt = make([]byte, 32)
if _, err = rand.Read(salt); err != nil {
return
}
}
key, err = scrypt.Key([]byte(password), salt, 32768, 8, 1, 32)
salt2 = salt
return
}
func encrypt(data, key []byte) (enc []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return
}
nonce := make([]byte, gcm.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return
}
enc = gcm.Seal(nonce, nonce, data, nil)
return
}
func decrypt(enc, key []byte) (data []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return
}
nonce := enc[:gcm.NonceSize()]
enc = enc[gcm.NonceSize():]
return gcm.Open(nil, nonce, enc, nil)
}