## 方式一
```
package aes
import (
"encoding/base64"
"fmt"
"github.com/forgoer/openssl"
)
const key = "abcdefgh87654321" // 16位字符串
// 加密
func Encrypt(src []byte) string {
keyByte:=[]byte(key)
dst , err := openssl.AesECBEncrypt(src, keyByte, openssl.PKCS7_PADDING)
if err != nil{
fmt.Println(err)
}
return base64.StdEncoding.EncodeToString(dst)
}
// 解密
func Decrypt(data string) (src []byte) {
src, err := base64.StdEncoding.DecodeString(data)
if err != nil{
fmt.Println(err)
return
}
keyByte:=[]byte(key)
src , err = openssl.AesECBDecrypt(src, keyByte, openssl.PKCS7_PADDING)
if err != nil{
fmt.Println(err)
}
return
}
```
## 方式二
```
package crypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"psoriasis/configs"
)
// 加密
func Encrypt(encryptStr string, key []byte) (string, error) {
encryptBytes := []byte(encryptStr)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
encryptBytes = PKCS5Padding(encryptBytes, blockSize)
iv := configs.CryptKey
blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
encrypted := make([]byte, len(encryptBytes))
blockMode.CryptBlocks(encrypted, encryptBytes)
return base64.StdEncoding.EncodeToString(encrypted), nil
}
// 解密
func Decrypt(decryptStr string, key []byte) (string, error) {
decryptBytes, err := base64.StdEncoding.DecodeString(decryptStr)
if err != nil {
return "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
iv := configs.CryptKey
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)]
}
```