54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"regexp"
|
|
)
|
|
|
|
// 解密函数
|
|
func Decrypt(ciphertext string, key []byte) (string, error) {
|
|
// Base64 解码
|
|
cipherTextDecoded, err := base64.StdEncoding.DecodeString(ciphertext)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// 创建 AES 密码块
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// 检查密文长度是否为块大小的倍数
|
|
if len(cipherTextDecoded)%aes.BlockSize != 0 {
|
|
return "", fmt.Errorf("密文长度不是块大小的倍数")
|
|
}
|
|
|
|
// 解密密文
|
|
decrypted := make([]byte, len(cipherTextDecoded))
|
|
for bs := 0; bs < len(cipherTextDecoded); bs += aes.BlockSize {
|
|
block.Decrypt(decrypted[bs:], cipherTextDecoded[bs:bs+aes.BlockSize])
|
|
}
|
|
|
|
// 移除填充
|
|
decrypted = pkcs7Unpad(decrypted)
|
|
|
|
// 移除不需要的字符
|
|
re := regexp.MustCompile("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]")
|
|
cleanedString := re.ReplaceAllString(string(decrypted), "")
|
|
|
|
return cleanedString, nil
|
|
}
|
|
|
|
// 移除PKCS7填充
|
|
func pkcs7Unpad(src []byte) []byte {
|
|
length := len(src)
|
|
unpadding := int(src[length-1])
|
|
if unpadding > length {
|
|
return src
|
|
}
|
|
return src[:(length - unpadding)]
|
|
}
|