62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
|
|
package meituan_csr
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"crypto/aes"
|
||
|
|
"encoding/base64"
|
||
|
|
)
|
||
|
|
|
||
|
|
type AES struct {
|
||
|
|
AesKey string
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewAes(aesKey string) *AES {
|
||
|
|
return &AES{
|
||
|
|
AesKey: aesKey,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *AES) Encode(data string) (string, error) {
|
||
|
|
_key := []byte(c.AesKey)
|
||
|
|
|
||
|
|
block, err := aes.NewCipher(_key)
|
||
|
|
if err != nil {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
// 计算需要补齐的字节数
|
||
|
|
paddingSize := block.BlockSize() - len([]byte(data))%block.BlockSize()
|
||
|
|
paddedText := append([]byte(data), bytes.Repeat([]byte{byte(paddingSize)}, paddingSize)...)
|
||
|
|
|
||
|
|
encryptedData := make([]byte, len(paddedText))
|
||
|
|
for i := 0; i < len(paddedText); i += block.BlockSize() {
|
||
|
|
block.Encrypt(encryptedData[i:], paddedText[i:]) // 分组加密
|
||
|
|
}
|
||
|
|
|
||
|
|
encodedString := base64.StdEncoding.EncodeToString(encryptedData) // Base64编码
|
||
|
|
return encodedString, nil
|
||
|
|
}
|
||
|
|
func (c *AES) Decode(data string) (str string, err error) {
|
||
|
|
_key := []byte(c.AesKey)
|
||
|
|
|
||
|
|
decodedBytes, err := base64.StdEncoding.DecodeString(data) // Base64解码
|
||
|
|
if err != nil {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
block, err := aes.NewCipher(_key) // 创建AES对象
|
||
|
|
if err != nil {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
decryptedData := make([]byte, len(decodedBytes))
|
||
|
|
for i := 0; i < len(decodedBytes); i += block.BlockSize() {
|
||
|
|
block.Decrypt(decryptedData[i:], decodedBytes[i:]) // 分组解密
|
||
|
|
}
|
||
|
|
unpadedText := c._PKCS5UnPadding(decryptedData) // 去除填充
|
||
|
|
return string(unpadedText), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func (c *AES) _PKCS5UnPadding(data []byte) []byte {
|
||
|
|
length := len(data)
|
||
|
|
unpadding := int(data[length-1])
|
||
|
|
return data[:(length - unpadding)]
|
||
|
|
}
|