-
Notifications
You must be signed in to change notification settings - Fork 1
/
sign_aes.go
63 lines (52 loc) · 1.56 KB
/
sign_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
package sign
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
// AesSign 对称加密
func AesSign(secretKey, body string) []byte {
ret, _ := Encrypt(body, []byte(secretKey), secretKey)
return []byte(ret)
}
// Encrypt 加密 aes_128_cbc
func Encrypt(encryptStr string, key []byte, iv string) (string, error) {
encryptBytes := []byte(encryptStr)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
encryptBytes = pkcs5Padding(encryptBytes, blockSize)
blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
encrypted := make([]byte, len(encryptBytes))
blockMode.CryptBlocks(encrypted, encryptBytes)
return base64.URLEncoding.EncodeToString(encrypted), nil
}
// Decrypt 解密
func Decrypt(decryptStr string, key []byte, iv string) (string, error) {
decryptBytes, err := base64.URLEncoding.DecodeString(decryptStr)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
decrypted := make([]byte, len(decryptBytes))
blockMode.CryptBlocks(decrypted, decryptBytes)
decrypted = pkcs5UnPadding(decrypted)
return string(decrypted), nil
}
func pkcs5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func pkcs5UnPadding(decrypted []byte) []byte {
length := len(decrypted)
unPadding := int(decrypted[length-1])
return decrypted[:(length - unPadding)]
}