使用Go语言crypto包实现AES-CBC加密,需密钥、随机IV和PKCS7填充;2. 加密时生成随机IV并前置密文,解密时提取IV并去除填充;3. 完整示例展示加密解密流程,输出Base64编码密文并成功还原明文。

在Go语言(Golang)中实现基础的加密解密功能并不复杂。借助标准库中的 crypto 包,比如 crypto/aes、crypto/cipher、crypto/rand 等,我们可以轻松构建安全的数据加解密模块。下面是一个基于AES对称加密算法(CBC模式)的简单项目示例,包含密钥生成、数据加密和解密功能。
AES(Advanced Encryption Standard)是一种广泛使用的对称加密算法。CBC(Cipher Block Chaining)模式能提高安全性,防止相同明文块生成相同密文。
加密过程需要:
以下是加密函数的实现:
立即学习“go语言免费学习笔记(深入)”;
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
<pre class='brush:php;toolbar:false;'>// 对明文进行PKCS7填充
plaintext = pkcs7Padding(plaintext, block.BlockSize())
// 初始化CBC加密器
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}
AES是分组加密算法,要求明文长度是块大小的整数倍(如16字节)。当数据不足时,需进行填充。
func pkcs7Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padtext...)
}
解密过程与加密相反:使用相同的密钥和IV(存储在密文前部),进行CBC解密,然后去除PKCS7填充。
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
<pre class='brush:php;toolbar:false;'>if len(ciphertext) < aes.BlockSize {
return nil, errors.New("密文过短")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
if len(ciphertext)%aes.BlockSize != 0 {
return nil, errors.New("密文长度不是块大小的整数倍")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
// 去除PKCS7填充
return pkcs7Unpadding(ciphertext)}
对应的去填充函数:
func pkcs7Unpadding(data []byte) ([]byte, error) {
length := len(data)
if length == 0 {
return nil, errors.New("空数据")
}
unpadding := int(data[length-1])
if unpadding > length {
return nil, errors.New("无效填充")
}
return data[:length-unpadding], nil
}
将上述函数整合到 main 函数中测试:
func main() {
key := []byte("1234567890123456") // 16字节密钥(AES-128)
plaintext := []byte("Hello, Golang加密解密示例!")
<pre class='brush:php;toolbar:false;'>ciphertext, err := encrypt(plaintext, key)
if err != nil {
log.Fatal("加密失败:", err)
}
fmt.Printf("密文(Base64): %s\n", base64.StdEncoding.EncodeToString(ciphertext))
decrypted, err := decrypt(ciphertext, key)
if err != nil {
log.Fatal("解密失败:", err)
}
fmt.Printf("解密结果: %s\n", string(decrypted))}
输出类似:
密文(Base64): wEvX...基本上就这些。这个项目展示了如何用Golang实现安全的基础加解密功能。你可以将其封装为独立包,支持更多模式(如GCM)或密钥派生(如PBKDF2),以适应实际应用需求。不复杂但容易忽略细节,比如IV的随机性和填充处理。
以上就是Golang实现基础加密解密功能项目的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号