-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
61 lines (46 loc) · 1.14 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
package blind
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
)
func Encrypt(key []byte, plain string) (string, error) {
plainBytes := []byte(plain)
block, blockErr := aes.NewCipher(key)
if blockErr != nil {
return "", blockErr
}
aesGCM, gcmErr := cipher.NewGCM(block)
if gcmErr != nil {
return "", gcmErr
}
nonce := make([]byte, aesGCM.NonceSize())
encrypted := aesGCM.Seal(nonce, nonce, plainBytes, nil)
return hex.EncodeToString(encrypted), nil
}
func GenerateCryptoKey(size int) ([]byte, error) {
bytes := make([]byte, size)
if _, err := rand.Read(bytes); err != nil {
return []byte{}, err
}
return bytes, nil
}
func Decrypt(key []byte, encrypted string) (string, error) {
enc, _ := hex.DecodeString(encrypted)
block, ncErr := aes.NewCipher(key)
if ncErr != nil {
return "", ncErr
}
aesGCM, gcmErr := cipher.NewGCM(block)
if gcmErr != nil {
return "", gcmErr
}
nonceSize := aesGCM.NonceSize()
nonce, ciphertext := enc[:nonceSize], enc[nonceSize:]
decrypted, openErr := aesGCM.Open(nil, nonce, ciphertext, nil)
if openErr != nil {
return "", openErr
}
return string(decrypted), nil
}