forked from yangmiok/thorchain-tss
/
encryption.go
53 lines (46 loc) · 1.14 KB
/
encryption.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
package common
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
// Encrypt the input data with passphrase
func AESEncrypt(data, derivedKey []byte) ([]byte, error) {
if len(data) == 0 || len(derivedKey) == 0 {
return nil, errors.New("invalid data or derivedkey")
}
block, _ := aes.NewCipher(derivedKey)
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext, nil
}
// AESDecrypt the input data with passphrase
func AESDecrypt(data, derivedKey []byte) ([]byte, error) {
if len(data) == 0 || len(derivedKey) == 0 {
return nil, errors.New("invalid data or derivedkey")
}
block, err := aes.NewCipher(derivedKey)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
nonce, ciphertext := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}