forked from LeoYoung-code/utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaes.go
More file actions
63 lines (55 loc) · 1.6 KB
/
aes.go
File metadata and controls
63 lines (55 loc) · 1.6 KB
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
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"strings"
)
// AesEncrypt 加密
func AesEncrypt(encodeStr string, key string, iv string, process func(crypt []byte) []byte) (string, error) {
encodeBytes := []byte(encodeStr)
// 根据key 生成密文
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
blockSize := block.BlockSize()
encodeBytes = PKCS5Padding(encodeBytes, blockSize)
blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
crypt := make([]byte, len(encodeBytes))
blockMode.CryptBlocks(crypt, encodeBytes)
if process != nil {
crypt = process(crypt)
}
return base64.StdEncoding.EncodeToString(crypt), nil
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
// 填充
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// AesDecrypt 解密
func AesDecrypt(decodeStr string, key []byte, iv string) ([]byte, error) {
// 先解密base64
decodeBytes, err := base64.StdEncoding.DecodeString(decodeStr)
if err != nil {
return nil, err
}
decodeBytes = []byte(strings.Replace(string(decodeBytes), iv, "", 1))
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
origData := make([]byte, len(decodeBytes))
blockMode.CryptBlocks(origData, decodeBytes)
origData = PKCS5UnPadding(origData)
return origData, nil
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unPadding := int(origData[length-1])
return origData[:(length - unPadding)]
}