generated from datumforge/go-template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
encrypt.go
59 lines (45 loc) · 1.23 KB
/
encrypt.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
package keygen
import (
"crypto/aes"
"crypto/cipher"
crand "crypto/rand"
"encoding/base64"
"io"
)
// Encrypt encrypts data with key (must be valid 32 char aes key).
func Encrypt(data []byte, key string) (string, error) {
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
// populates the nonce with a cryptographically secure random sequence
if _, err := io.ReadFull(crand.Reader, nonce); err != nil {
return "", err
}
cipherByte := gcm.Seal(nonce, nonce, data, nil)
result := base64.StdEncoding.EncodeToString(cipherByte)
return result, nil
}
// Decrypt decrypts encrypted text with key (must be valid 32 chars aes key).
func Decrypt(cipherText string, key string) ([]byte, error) {
block, err := aes.NewCipher([]byte(key))
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
cipherByte, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return nil, err
}
nonce, cipherByteClean := cipherByte[:nonceSize], cipherByte[nonceSize:]
return gcm.Open(nil, nonce, cipherByteClean, nil)
}