1. go版本接入样例
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
)
type Demo struct {
Key string `json:"key"`
}
func main() {
secretKey := "XXX"
demo := &Demo{Key: "val"}
str, _ := json.Marshal(demo)
es, _ := AesEncrypt(str, []byte(secretKey))
fmt.Println(es)
ds, _ := AesDecrypt(es, []byte(secretKey))
fmt.Println(string(ds))
}
func AesEncrypt(encodeBytes []byte, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
encodeBytes = PKCS5Padding(encodeBytes, blockSize)
md5Str := GetMD5Hash(key)
blockMode := cipher.NewCBCEncrypter(block, []byte(md5Str))
crypted := make([]byte, len(encodeBytes))
blockMode.CryptBlocks(crypted, encodeBytes)
encoding := base64.StdEncoding.EncodeToString(crypted)
return base64.StdEncoding.EncodeToString([]byte(encoding)), nil
}
func GetMD5Hash(text []byte) string {
hash := md5.Sum(text)
return hex.EncodeToString(hash[:])[:16]
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func AesDecrypt(decodeStr string, key []byte) ([]byte, error) {
decodeBytes, err := base64.StdEncoding.DecodeString(decodeStr)
if err != nil {
return nil, err
}
decodeBytes, err = base64.StdEncoding.DecodeString(string(decodeBytes))
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
md5Str := GetMD5Hash(key)
blockMode := cipher.NewCBCDecrypter(block, []byte(md5Str))
origData := make([]byte, len(decodeBytes))
blockMode.CryptBlocks(origData, decodeBytes)
origData = PKCS5UnPadding(origData)
return origData, nil
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}