-
Notifications
You must be signed in to change notification settings - Fork 139
/
aes.go
61 lines (56 loc) · 1.34 KB
/
aes.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 cryptox
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5" // #nosec
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"github.com/zeromicro/go-zero/core/logx"
)
func createHash(key string) string {
hasher := md5.New() // #nosec
_, err := hasher.Write([]byte(key))
if err != nil {
logx.Error(err)
}
return hex.EncodeToString(hasher.Sum(nil))
}
func EncryptAES(data []byte, passphrase string) []byte {
block, _ := aes.NewCipher([]byte(createHash(passphrase)))
gcm, err := cipher.NewGCM(block)
if err != nil {
fmt.Println("encrypt ", string(data), "failed", err)
return nil
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
fmt.Println("encrypt ", string(data), "failed", err)
return nil
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
return ciphertext
}
func DecryptAES(data []byte, passphrase string) ([]byte, error) {
if len(data) < 12 {
return nil, errors.New("data too short")
}
key := []byte(createHash(passphrase))
block, err := aes.NewCipher(key)
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
}