crypto AES 对称加密
AES 对称加密
使用 AES 进行对称加密在 Go 中可以通过crypto/aes和crypto/cipher包来实现。下面是一个简单的示例,演示如何使用 AES 进行加密和解密。
AES 对称加密和解密示例
1. 安装 Go 环境
确保你已经安装并配置好了 Go 编程环境。
2. 编写代码
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
)
// 生成一个32字节的密钥(AES-256)
func generateKey(passphrase string) []byte {
hash := sha256.Sum256([]byte(passphrase))
return hash[:]
}
// AES加密
func encrypt(plaintext, key []byte) (ciphertext []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 创建一个新的GCM模式实例
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// 创建一个随机的nonce(唯一值)
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
// 使用GCM进行加密
ciphertext = gcm.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
// AES解密
func decrypt(ciphertext, key []byte) (plaintext []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 创建一个新的GCM模式实例
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// 提取nonce
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
// 使用GCM进行解密
plaintext, err = gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
func main() {
passphrase := "my secret passphrase"
key := generateKey(passphrase)
plaintext := []byte("Hello, World!")
fmt.Printf("Original text: %s\n", plaintext)
// 加密
ciphertext, err := encrypt(plaintext, key)
if err != nil {
fmt.Printf("Encryption failed: %v\n", err)
return
}
fmt.Printf("Encrypted text: %s\n", hex.EncodeToString(ciphertext))
// 解密
decryptedText, err := decrypt(ciphertext, key)
if err != nil {
fmt.Printf("Decryption failed: %v\n", err)
return
}
fmt.Printf("Decrypted text: %s\n", decryptedText)
}
代码说明
-
生成密钥:
generateKey函数使用 SHA-256 哈希函数生成一个 32 字节的密钥。你可以根据需要修改密钥生成方式。 -
AES 加密:
encrypt函数执行以下步骤:- 创建一个 AES 密码块。
- 使用 GCM 模式(Galois/Counter Mode)包装密码块。
- 生成一个随机的 nonce。
- 使用 GCM 模式进行 加密,将 nonce 和密文组合在一起返回。
-
AES 解密:
decrypt函数执行以下步骤:- 创建一个 AES 密码块。
- 使用 GCM 模式包装密码块。
- 从密文中提取 nonce。
- 使用 GCM 模式进行解密,返回明文。
-
主函数:
main函数演示了如何使用上述函数进行加密和解密操作。
运行代码
将上述代码保存为一个.go文件(例如aes_example.go),然后在终端运行以下命令:
go run aes_example.go
你将看到加密和解密的输出结果。这个示例展示了如何使用 AES 进行对称加密和解密,实际使用中请确保密钥和 nonce 的安全性 。