以下是一个使用 Go 语言实现 AES
加密和解密的示例代码:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
// 加密函数
func encryptAES(key []byte, plaintext []byte) ([]byte, error) {
// 创建一个新的 AES 加密块
block, err := aes.NewCipher(key)
if err!= nil {
return nil, err
}
// 创建一个 GCM 模式的 AEAD (Authenticated Encryption with Associated Data)
aesGCM, err := cipher.NewGCM(block)
if err!= nil {
return nil, err
}
// 生成随机的 nonce
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err!= nil {
return nil, err
}
// 加密并添加认证标签
ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
// 解密函数
func decryptAES(key []byte, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err!= nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err!= nil {
return nil, err
}
nonceSize := aesGCM.NonceSize()
if len(ciphertext) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
}
// 提取 nonce 和密文
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
// 解密
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
if err!= nil {
return nil, err
}
return plaintext, nil
}
func main() {
// 密钥(必须是 16、24 或 32 字节)
key := []byte("my_secret_key_1234567890")
plaintext := []byte("Hello, AES!")
ciphertext, err := encryptAES(key, plaintext)
if err!= nil {
fmt.Println("Encryption error:", err)
return
}
fmt.Printf("Ciphertext: %x\n", ciphertext)
decryptedText, err := decryptAES(key, ciphertext)
if err!= nil {
fmt.Println("Decryption error:", err)
return
}
fmt.Printf("Decrypted text: %s\n", decryptedText)
}
在上述代码中:
encryptAES
函数使用给定的密钥对明文进行AES
加密,并生成随机的nonce
。decryptAES
函数使用相同的密钥和提取的nonce
对密文进行解密。
请注意,在实际应用中,密钥的管理和保护非常重要。