71 lines
1.7 KiB
Go
71 lines
1.7 KiB
Go
package utils
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"encoding/base64"
|
|
"errors"
|
|
)
|
|
|
|
func pkcs7Padding(data []byte, blockSize int) []byte {
|
|
padding := blockSize - len(data)%blockSize
|
|
padText := bytes.Repeat([]byte{byte(padding)}, padding)
|
|
return append(data, padText...)
|
|
}
|
|
|
|
func pkcs7UnPadding(data []byte) ([]byte, error) {
|
|
length := len(data)
|
|
if length == 0 {
|
|
return nil, errors.New("加密字符串为空!")
|
|
}
|
|
unPadding := int(data[length-1])
|
|
return data[:(length - unPadding)], nil
|
|
}
|
|
|
|
func aesEncrypt(data []byte, key []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
blockSize := block.BlockSize()
|
|
encryptBytes := pkcs7Padding(data, blockSize)
|
|
encrypted := make([]byte, len(encryptBytes))
|
|
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
|
|
blockMode.CryptBlocks(encrypted, encryptBytes)
|
|
return encrypted, nil
|
|
}
|
|
|
|
func aesDecrypt(data []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])
|
|
decrypted := make([]byte, len(data))
|
|
blockMode.CryptBlocks(decrypted, data)
|
|
//fmt.Println(data, decrypted)
|
|
decrypted, err = pkcs7UnPadding(decrypted)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return decrypted, err
|
|
}
|
|
|
|
func EncryptByAes(data []byte, key []byte) (string, error) {
|
|
res, err := aesEncrypt(data, key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return base64.StdEncoding.EncodeToString(res), nil
|
|
}
|
|
|
|
func DecryptByAes(data string, key []byte) ([]byte, error) {
|
|
dataByte, err := base64.StdEncoding.DecodeString(data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return aesDecrypt(dataByte, key)
|
|
}
|