package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
)
// EncryptAES 使用 AES 算法对数据进行加密
func EncryptAES(plaintext string, key []byte) (string, error) {
// 创建 AES 加密算法实例
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// 对原始数据进行填充,使其长度是块大小的整数倍
plaintextBytes := []byte(plaintext)
plaintextBytes = PKCS5Padding(plaintextBytes, aes.BlockSize)
// 加密
ciphertext := make([]byte, aes.BlockSize+len(plaintextBytes))
iv := ciphertext[:aes.BlockSize] // 初始向量 IV 的长度与块大小相同
if _, err := io.ReadFull(rand.Reader, iv); err != nil { // 生成随机的 IV
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintextBytes)
// 将加密结果转换为十六进制字符串
encrypted := hex.EncodeToString(ciphertext)
return encrypted, nil
}
// PKCS5Padding 使用 PKCS5 填充对数据进行填充,使其长度是 blockSize 的整数倍
func PKCS5Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
// DecryptAES 使用 AES 算法对密文进行解密
func DecryptAES(encrypted string, key []byte) (string, error) {
// 将十六进制字符串解码为字节
ciphertext, err := hex.DecodeString(encrypted)
if err != nil {
return "", err
}
// 创建 AES 解密算法实例
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// 解密
if len(ciphertext) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
// 去除填充,并将结果转换为字符串
plaintext := string(ciphertext)
return plaintext, nil
}
func main() {
// 原始数据
plaintext := "123413253464564514312341232351324`34"
// 加密密钥,AES密钥长度为 16, 24, 或 32 字节,对应 AES-128, AES-192, 或 AES-256
key := []byte("0123456789abcdef0123456789abcdef")
// 加密
encrypted, err := EncryptAES(plaintext, key)
if err != nil {
panic(err)
}
fmt.Printf("Encrypted: %s\n", encrypted)
// 解密
decrypted, err := DecryptAES(encrypted, key)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted: %s\n", decrypted)
}
01-20
09-09
423
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-21
3761
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-20
4374
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交