Appearance
Go加解密示例代码
go
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
func Encrypt(plaintext, key []byte) ([]byte, error) {
return EncryptWithIV(plaintext, key, []byte("0000000000000000"))
}
func EncryptWithIV(plaintext, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 检查IV长度
if len(iv) != aes.BlockSize {
return nil, fmt.Errorf("无效的IV长度,期望%d字节,实际%d字节", aes.BlockSize, len(iv))
}
// 添加PKCS#5填充
plaintext = pkcs5Padding(plaintext, aes.BlockSize)
// CBC模式加密
mode := cipher.NewCBCEncrypter(block, iv)
ciphertext := make([]byte, len(plaintext))
mode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
func Decrypt(ciphertext, key []byte) ([]byte, error) {
return DecryptWithIV(ciphertext, key, []byte("0000000000000000"))
}
func DecryptWithIV(ciphertext, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 检查IV长度
if len(iv) != aes.BlockSize {
return nil, fmt.Errorf("无效的IV长度,期望%d字节,实际%d字节", aes.BlockSize, len(iv))
}
// CBC模式解密
mode := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
// 移除PKCS#5填充
return pkcs5Unpadding(plaintext), nil
}
// 添加PKCS#5填充
func pkcs5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := make([]byte, padding)
for i := range padtext {
padtext[i] = byte(padding)
}
return append(src, padtext...)
}
// 移除PKCS#5填充
func pkcs5Unpadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
func main() {
keyBase64 := "Q2OWXUJMliSdRBkIZyKMlFkytQbeCQPYcrzRoAM2Wus="
key, err := base64.StdEncoding.DecodeString(keyBase64)
if err != nil {
fmt.Printf("密钥解码错误: %v\n", err)
return
}
fmt.Printf("密钥长度: %d 字节\n\n", len(key))
source := []byte(`{"outerTradeNo":"D202410010000000004","realName":"凌小云","phone":"17666666666","idCard":"50000000001","idCardType":1,"payAccount":"17666666666","reason":"推广费用","balance":5.2,"bizAccount":"13888888888","taskId":1}`)
// 加密
ciphertext, err := Encrypt(source, key)
if err != nil {
fmt.Printf("加密错误: %v\n", err)
return
}
ciphertextBase64 := base64.StdEncoding.EncodeToString(ciphertext)
fmt.Printf("加密:\n%s\n\n", ciphertextBase64)
// 解密
decrypted, err := Decrypt(ciphertext, key)
if err != nil {
fmt.Printf("解密错误: %v\n", err)
return
}
fmt.Printf("解密: \n%s\n\n", string(decrypted))
}