You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.6 KiB
75 lines
1.6 KiB
package util
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"encoding/base64"
|
|
"strings"
|
|
)
|
|
|
|
var aesKey []byte
|
|
|
|
func init() {
|
|
aesKey = []byte("11e90a62f2fa07ce9e600242ac110007")
|
|
}
|
|
|
|
func pkcs7Padding(src []byte, blockSize int) []byte {
|
|
padding := blockSize - len(src)%blockSize
|
|
padText := bytes.Repeat([]byte{byte(padding)}, padding)
|
|
return append(src, padText...)
|
|
}
|
|
|
|
func aesEncrypt(src, key []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
blockSize := block.BlockSize()
|
|
src = pkcs7Padding(src, blockSize)
|
|
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
|
|
encrypted := make([]byte, len(src))
|
|
blockMode.CryptBlocks(encrypted, src)
|
|
return encrypted, nil
|
|
}
|
|
|
|
func aesDecrypt(encrypted, key []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
blockSize := block.BlockSize()
|
|
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
|
|
src := make([]byte, len(encrypted))
|
|
blockMode.CryptBlocks(src, encrypted)
|
|
src = pkcs7UnPadding(src)
|
|
return src, nil
|
|
}
|
|
|
|
func pkcs7UnPadding(src []byte) []byte {
|
|
length := len(src)
|
|
unPadding := int(src[length-1])
|
|
return src[:(length - unPadding)]
|
|
}
|
|
|
|
func AesEncrypt(src string) (string, error) {
|
|
res, err := aesEncrypt([]byte(src), aesKey)
|
|
if err != nil {
|
|
r := base64.StdEncoding.EncodeToString(res)
|
|
return r, nil
|
|
} else {
|
|
return "", err
|
|
}
|
|
}
|
|
|
|
func AesDecrypt(src string) (string, error) {
|
|
if len(src) == 0 || strings.TrimSpace(src) == "" {
|
|
return "", nil
|
|
}
|
|
s, e := base64.StdEncoding.DecodeString(src)
|
|
if e != nil {
|
|
return "", e
|
|
}
|
|
res, err := aesDecrypt(s, aesKey)
|
|
return string(res), err
|
|
}
|