-
Notifications
You must be signed in to change notification settings - Fork 1
/
aes.go
104 lines (96 loc) · 2.58 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
104
package function
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
)
var password = []byte("6D05CDFD6288ADE9")
// PKCS7Padding PKCS7 填充模式
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padText...)
}
// PKCS7UnPadding 填充的反向操作,删除填充字符串
func PKCS7UnPadding(origData []byte) ([]byte, error) {
//获取数据长度
length := len(origData)
if length == 0 {
return nil, errors.New("加密字符串错误!")
} else {
//获取填充字符串长度
unPadding := int(origData[length-1])
//截取切片,删除填充字节,并且返回明文
return origData[:(length - unPadding)], nil
}
}
// AesEncrypt 实现加密
func AesEncrypt(origData []byte, key []byte) ([]byte, error) {
//创建加密算法实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//获取块的大小
blockSize := block.BlockSize()
//对数据进行填充,让数据长度满足需求
origData = PKCS7Padding(origData, blockSize)
//采用AES加密方法中CBC加密模式
blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
encrypted := make([]byte, len(origData))
//执行加密
blocMode.CryptBlocks(encrypted, origData)
return encrypted, nil
}
// AesDecrypt 实现解密
func AesDecrypt(encrypted []byte, key []byte) ([]byte, error) {
//创建加密算法实例
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//获取块大小
blockSize := block.BlockSize()
//创建加密客户端实例
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(encrypted))
//这个函数也可以用来解密
blockMode.CryptBlocks(origData, encrypted)
//去除填充字符串
origData, err = PKCS7UnPadding(origData)
if err != nil {
return nil, err
}
return origData, err
}
// AesEncryptBase64 加密为base64
func AesEncryptBase64(str, key string) (string, error) {
if key != "" {
password = []byte(key)
}
result, err := AesEncrypt([]byte(str), password)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(result), err
}
// AesDecryptBase64 base64解密
func AesDecryptBase64(str, key string) (string, error) {
if key != "" {
password = []byte(key)
}
//解密base64字符串
pwdByte, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return "", err
}
var b []byte
//执行AES解密
b, err = AesDecrypt(pwdByte, password)
if err == nil {
return string(b), nil
}
return "", err
}