-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaes.go
69 lines (61 loc) · 1.13 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
62
63
64
65
66
67
68
69
package encryption
import (
"crypto/aes"
"crypto/cipher"
)
// AESCtrCipher .
type AESCtrCipher struct {
key []byte
nonce []byte
}
var iv = []byte("1s2z2SS0cg5a11a0")
// NewAESCtrCipher initializes AESCipher
func NewAESCtrCipher(key []byte) *AESCtrCipher {
_, err := aes.NewCipher(key)
if err != nil {
return nil
}
return &AESCtrCipher{key: key, nonce: iv}
}
// Encrypt 加密
func (a *AESCtrCipher) Encrypt(src []byte) []byte {
if a == nil {
return nil
}
cip, err := aes.NewCipher(a.key)
if err != nil {
return nil
}
blockMode := cipher.NewCTR(cip, a.nonce)
res := make([]byte, len(src))
blockMode.XORKeyStream(res, src)
return res
}
// Decrypt 解密
func (a *AESCtrCipher) Decrypt(src []byte) []byte {
if a == nil {
return nil
}
cip, err := aes.NewCipher(a.key)
if err != nil {
return nil
}
blockMode := cipher.NewCTR(cip, a.nonce)
res := make([]byte, len(src))
blockMode.XORKeyStream(res, src)
return res
}
// GetKey .
func (a *AESCtrCipher) GetKey() []byte {
if a == nil {
return nil
}
return a.key
}
// GetNonce .
func (a *AESCtrCipher) GetNonce() []byte {
if a == nil {
return nil
}
return a.nonce
}