package common import ( "crypto/aes" "crypto/cipher" "encoding/base64" "github.com/gogf/gf/v2/crypto/gmd5" "strings" ) // 假设p()就是md5 func p(data string) []byte { return []byte(gmd5.MustEncryptString(data)) } //func p(hexStr string) []byte { // bytes, _ := hex.DecodeString(hexStr) // return bytes //} func Encrypt(plaintext string, keyPrefix string) (string, error) { // 生成key和iv key := p(keyPrefix + "piaofan@123") iv := p(keyPrefix + "piaofan@456")[:16] // plaintext to bytes plaintextBytes := []byte(plaintext) // 创建AES加密器 block, err := aes.NewCipher(key) if err != nil { return "", err } // 初始化CBC模式 stream := cipher.NewCBCEncrypter(block, iv) // 加密 ciphertext := make([]byte, len(plaintextBytes)) stream.CryptBlocks(ciphertext, plaintextBytes) // 返回base64编码的ciphertext return base64.StdEncoding.EncodeToString(ciphertext), nil } func Decrypt(base64Ciphertext string, keyPrefix string) (string, error) { // base64解码ciphertext ciphertext, err := base64.StdEncoding.DecodeString(base64Ciphertext) if err != nil { return "", err } // 生成key和iv key := p(keyPrefix + "piaofan@123") iv := p(keyPrefix + "piaofan@456")[:16] //g.Log().Infof(context.Background(), "key: %s", gconv.String(key)) // 创建AES解密器 block, err := aes.NewCipher(key) if err != nil { return "", err } // 初始化CBC模式 stream := cipher.NewCBCDecrypter(block, iv) // 解密 plaintext := make([]byte, len(ciphertext)) stream.CryptBlocks(plaintext, ciphertext) return strings.TrimSpace(string(plaintext)), nil }