| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213 | package aesimport (	"bytes"	"crypto/aes"	"crypto/cipher"	"crypto/rand"	"encoding/base64"	"encoding/hex"	"errors"	"fmt"	"io")// KEY_ALGORITHM 密钥算法const KEY_ALGORITHM = "AES"// DEFAULT_CIPHER_ALGORITHM 默认加密算法/工作模式/填充方式const DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"// InitSecretKey 初始化密钥func InitSecretKey() ([]byte, error) {	key := make([]byte, 16) // AES-128	if _, err := io.ReadFull(rand.Reader, key); err != nil {		return nil, fmt.Errorf("生成随机密钥失败: %v", err)	}	return key, nil}// ToKey 转换密钥func ToKey(key []byte) cipher.Block {	block, _ := aes.NewCipher(key)	return block}// Encrypt 加密func Encrypt(data, key []byte) ([]byte, error) {	return EncryptWithAlgorithm(data, key, DEFAULT_CIPHER_ALGORITHM)}// EncryptWithAlgorithm 使用指定算法加密func EncryptWithAlgorithm(data, key []byte, cipherAlgorithm string) ([]byte, error) {	block := ToKey(key)	// PKCS5填充	data = PKCS5Padding(data, block.BlockSize())	ciphertext := make([]byte, len(data))	for bs, be := 0, block.BlockSize(); bs < len(data); bs, be = bs+block.BlockSize(), be+block.BlockSize() {		block.Encrypt(ciphertext[bs:be], data[bs:be])	}	return ciphertext, nil}// Decrypt 解密func Decrypt(data, key []byte) ([]byte, error) {	return DecryptWithAlgorithm(data, key, DEFAULT_CIPHER_ALGORITHM)}// DecryptWithAlgorithm 使用指定算法解密func DecryptWithAlgorithm(data, key []byte, cipherAlgorithm string) ([]byte, error) {	block := ToKey(key)	plaintext := make([]byte, len(data))	for bs, be := 0, block.BlockSize(); bs < len(data); bs, be = bs+block.BlockSize(), be+block.BlockSize() {		block.Decrypt(plaintext[bs:be], data[bs:be])	}	// PKCS5去除填充	plaintext = PKCS5UnPadding(plaintext)	return plaintext, nil}// ShowByteArray 显示字节数组func ShowByteArray(data []byte) string {	if data == nil {		return "nil"	}	var buf bytes.Buffer	buf.WriteString("{")	for i, b := range data {		if i > 0 {			buf.WriteString(",")		}		buf.WriteString(fmt.Sprintf("%d", b))	}	buf.WriteString("}")	return buf.String()}// ParseHexStr2Byte 将16进制转换为二进制func ParseHexStr2Byte(hexStr string) ([]byte, error) {	if len(hexStr) < 1 {		return nil, errors.New("hex string too short")	}	return hex.DecodeString(hexStr)}// ParseByte2HexStr 将二进制转换成16进制func ParseByte2HexStr(data []byte) string {	return hex.EncodeToString(data)}// AESEncryptString 加密字符串func AESEncryptString(str, key string) (string, error) {	if str == "" || key == "" {		return "", errors.New("input string or key is empty")	}	keyBytes := []byte(key)	if len(keyBytes) != 16 && len(keyBytes) != 24 && len(keyBytes) != 32 {		return "", errors.New("key length must be 16, 24 or 32 bytes")	}	block, err := aes.NewCipher(keyBytes)	if err != nil {		return "", fmt.Errorf("创建AES加密块失败: %v", err)	}	// PKCS5填充	data := PKCS5Padding([]byte(str), block.BlockSize())	ciphertext := make([]byte, len(data))	for bs, be := 0, block.BlockSize(); bs < len(data); bs, be = bs+block.BlockSize(), be+block.BlockSize() {		block.Encrypt(ciphertext[bs:be], data[bs:be])	}	return base64.StdEncoding.EncodeToString(ciphertext), nil}// AESDecryptString 解密字符串func AESDecryptString(str, key string) (string, error) {	if str == "" || key == "" {		return "", errors.New("input string or key is empty")	}	keyBytes := []byte(key)	if len(keyBytes) != 16 && len(keyBytes) != 24 && len(keyBytes) != 32 {		return "", errors.New("key length must be 16, 24 or 32 bytes")	}	ciphertext, err := base64.StdEncoding.DecodeString(str)	if err != nil {		return "", fmt.Errorf("base64解码失败: %v", err)	}	block, err := aes.NewCipher(keyBytes)	if err != nil {		return "", fmt.Errorf("创建AES加密块失败: %v", err)	}	plaintext := make([]byte, len(ciphertext))	for bs, be := 0, block.BlockSize(); bs < len(ciphertext); bs, be = bs+block.BlockSize(), be+block.BlockSize() {		block.Decrypt(plaintext[bs:be], ciphertext[bs:be])	}	// PKCS5去除填充	plaintext = PKCS5UnPadding(plaintext)	return string(plaintext), nil}// PKCS5Padding PKCS5填充func PKCS5Padding(data []byte, blockSize int) []byte {	padding := blockSize - len(data)%blockSize	padText := bytes.Repeat([]byte{byte(padding)}, padding)	return append(data, padText...)}// PKCS5UnPadding PKCS5去除填充func PKCS5UnPadding(data []byte) []byte {	length := len(data)	unPadding := int(data[length-1])	return data[:(length - unPadding)]}// ExampleUsage 示例用法func ExampleUsage() {	// 示例密钥(与Java示例中的密钥一致)	exampleKeyBase64 := "9iEepr1twrizIEKrs1hs2A=="	exampleKey, _ := base64.StdEncoding.DecodeString(exampleKeyBase64)	// 示例数据	exampleData := `{"requestName":"BeforeIn","requestValue":{"carCode":"浙AD0V07","inTime":"2016-09-29 10:06:03","inChannelId":"4","GUID":"1403970b-4eb2-46bc-8f2b-eeec91ddcd5f","inOrOut":"0"},"Type":"0"}`	fmt.Printf("加密前数据: string: %s\n", exampleData)	fmt.Printf("加密前数据: byte[]: %s\n", ShowByteArray([]byte(exampleData)))	fmt.Println()	// 加密	encryptData, err := Encrypt([]byte(exampleData), exampleKey)	if err != nil {		fmt.Printf("加密失败: %v\n", err)		return	}	encryptStr := ParseByte2HexStr(encryptData)	fmt.Printf("加密后数据: byte[]: %s\n", ShowByteArray(encryptData))	fmt.Printf("加密后数据: Byte2HexStr: %s\n", encryptStr)	fmt.Println()	// 解密	decryptData, err := Decrypt(encryptData, exampleKey)	if err != nil {		fmt.Printf("解密失败: %v\n", err)		return	}	fmt.Printf("解密后数据: byte[]: %s\n", ShowByteArray(decryptData))	fmt.Printf("解密后数据: string: %s\n", string(decryptData))}
 |