-
Notifications
You must be signed in to change notification settings - Fork 3
/
aes.go
103 lines (81 loc) · 2.35 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package gocrypto
// 对称加密AES,高级加密标准,安全度最高,已逐渐替代DES成为新一代对称加密的标准
import (
"encoding/hex"
"errors"
"github.com/zhufuyi/pkg/gocrypto/comCipher"
)
// AesEncrypt aes加密byte,返回的密文未经过转码
func AesEncrypt(rawData []byte, opts ...AesOption) ([]byte, error) {
o := defaultAesOptions()
o.apply(opts...)
return aesEncrypt(o.mode, rawData, o.aesKey)
}
// AesDecrypt aes解密byte,参数输入未经过转码的密文
func AesDecrypt(cipherData []byte, opts ...AesOption) ([]byte, error) {
o := defaultAesOptions()
o.apply(opts...)
return aesDecrypt(o.mode, cipherData, o.aesKey)
}
// AesEncryptHex aes加密string,返回的密文已经转码
func AesEncryptHex(rawData string, opts ...AesOption) (string, error) {
o := defaultAesOptions()
o.apply(opts...)
cipherData, err := aesEncrypt(o.mode, []byte(rawData), o.aesKey)
if err != nil {
return "", err
}
return hex.EncodeToString(cipherData), nil
}
// AesDecryptHex aes解密string,参数输入已经转码的密文字符串
func AesDecryptHex(cipherStr string, opts ...AesOption) (string, error) {
o := defaultAesOptions()
o.apply(opts...)
cipherData, err := hex.DecodeString(cipherStr)
if err != nil {
return "", err
}
rawData, err := aesDecrypt(o.mode, cipherData, o.aesKey)
if err != nil {
return "", err
}
return string(rawData), nil
}
func getCipherMode(mode string) (comCipher.CipherMode, error) {
var cipherMode comCipher.CipherMode
switch mode {
case modeECB:
cipherMode = comCipher.NewECBMode()
case modeCBC:
cipherMode = comCipher.NewCBCMode()
case modeCFB:
cipherMode = comCipher.NewCFBMode()
case modeCTR:
cipherMode = comCipher.NewCTRMode()
default:
return nil, errors.New("unknown mode = " + mode)
}
return cipherMode, nil
}
func aesEncrypt(mode string, rawData []byte, key []byte) ([]byte, error) {
cipherMode, err := getCipherMode(mode)
if err != nil {
return nil, err
}
cip, err := comCipher.NewAESWith(key, cipherMode)
if err != nil {
return nil, err
}
return cip.Encrypt(rawData), nil
}
func aesDecrypt(mode string, cipherData []byte, key []byte) ([]byte, error) {
cipherMode, err := getCipherMode(mode)
if err != nil {
return nil, err
}
cip, err := comCipher.NewAESWith(key, cipherMode)
if err != nil {
return nil, err
}
return cip.Decrypt(cipherData), nil
}