golang中使用aes加密的操作方法
作者:JO22Zs68T
AES是一种对称加密算法,适用于加密敏感数据,通过上述方法,可在 Golang中实现AES加密/解密功能,本文给大家介绍golang中使用aes加密的操作方法,感兴趣的朋友跟随小编一起看看吧
AES 加密基础
AES(Advanced Encryption Standard)是一种对称加密算法,适用于加密敏感数据。Golang 的 crypto/aes 包提供了 AES 加密的实现,通常结合 crypto/cipher 包使用。
生成密钥
AES 密钥长度需为 16(AES-128)、24(AES-192)或 32(AES-256)字节。
key := []byte("32-byte-long-key-here-1234567890") // AES-256 密钥
加密数据
使用 CBC 模式(需填充)和随机 IV(初始化向量):
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 填充数据到块大小
plaintext = pkcs7Pad(plaintext, aes.BlockSize)
// 生成随机 IV
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
// 加密
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return ciphertext, nil
}
// PKCS7 填充
func pkcs7Pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}解密数据
解密时需提取 IV 并移除填充:
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
// 解密
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
// 移除填充
ciphertext = pkcs7Unpad(ciphertext)
return ciphertext, nil
}
// PKCS7 去填充
func pkcs7Unpad(data []byte) []byte {
length := len(data)
unpadding := int(data[length-1])
return data[:(length - unpadding)]
}使用 GCM 模式(推荐)
GCM(Galois/Counter Mode)提供认证加密,无需手动填充:
func encryptGCM(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func decryptGCM(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, fmt.Errorf("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}注意事项
- 密钥管理:密钥需安全存储,避免硬编码。
- IV/Nonce:每次加密需生成随机 IV 或 Nonce,禁止重复使用。
- 性能:GCM 模式适合高性能场景,CBC 需手动处理填充。
通过上述方法,可在 Golang 中实现 AES 加密/解密功能,根据需求选择 CBC 或 GCM 模式。
到此这篇关于golang中使用aes加密的文章就介绍到这了,更多相关go aes加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
