Golangcrypto加密解密详解教程
时间:2025-09-27 19:55:32 399浏览 收藏
本文详细讲解了如何在 Golang 中使用 `crypto` 包进行 AES 加密和解密,特别关注了安全性问题。文章首先介绍了 AES 对称加密的 CBC 模式,包括密钥生成、IV 随机生成、PKCS7 填充等关键步骤,并提供了示例代码。同时强调了密钥安全管理的重要性。更进一步,文章推荐使用 GCM 模式,这是一种 AEAD 模式,能提供更高级别的安全性和完整性校验,并给出了 GCM 模式的示例代码。此外,文章还提醒开发者在使用 `crypto/rand` 生成安全随机数、避免硬编码密钥以及防范其他常见安全漏洞。通过学习本文,开发者可以掌握 Golang 中 `crypto` 包的基本用法,并能应用于实际的安全需求中。
Go语言crypto包支持AES对称加密,推荐使用GCM模式。示例展示了CBC和GCM两种模式的加解密实现,强调密钥安全管理、IV随机生成及PKCS7填充处理,避免安全漏洞。

Go语言的crypto包提供了丰富的加密功能,适用于常见的安全需求。它包含多个子包,如crypto/aes、crypto/des、crypto/rand等,支持对称加密、非对称加密和哈希算法。下面介绍几种基础的加密与解密方法,以AES对称加密为例说明如何在Go中实现数据加解密。
AES对称加密(CBC模式)
AES(Advanced Encryption Standard)是最常用的对称加密算法之一。使用AES进行加密时,需要一个密钥(key)和初始化向量(IV),推荐使用CBC(Cipher Block Chaining)模式以增强安全性。
注意: 密钥长度必须是16、24或32字节,分别对应AES-128、AES-192和AES-256。
步骤说明:
- 生成密钥和IV(实际应用中应安全存储密钥,IV可随机生成并随密文传输)
- 使用
cipher.NewCBCEncrypter进行加密 - 使用
cipher.NewCBCDecrypter进行解密 - 处理明文填充(常用PKCS7)
示例代码:
package main
<p>import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)</p><p>func pkcs7Padding(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padtext := make([]byte, padding)
for i := range padtext {
padtext[i] = byte(padding)
}
return append(data, padtext...)
}</p><p>func pkcs7Unpadding(data []byte) []byte {
length := len(data)
if length == 0 {
return nil
}
unpadding := int(data[length-1])
if unpadding > length {
return nil
}
return data[:(length - unpadding)]
}</p><p>func AESEncrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}</p><pre class="brush:php;toolbar:false"><code>plaintext = pkcs7Padding(plaintext, block.BlockSize())
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</code>}
func AESDecrypt(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:]
if len(ciphertext)%block.BlockSize() != 0 {
return nil, fmt.Errorf("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
return pkcs7Unpadding(ciphertext), nil}
func main() { key := []byte("example key 1234") // 16字节密钥 plaintext := []byte("Hello, this is a secret message!")
ciphertext, err := AESEncrypt(plaintext, key)
if err != nil {
panic(err)
}
fmt.Printf("Ciphertext: %x\n", ciphertext)
decrypted, err := AESDecrypt(ciphertext, key)
if err != nil {
panic(err)
}
fmt.Printf("Decrypted: %s\n", decrypted)}
使用crypto/rand生成安全随机数
在加密过程中,初始化向量(IV)或盐值(salt)应使用密码学安全的随机数生成器。crypto/rand提供了这样的接口。
示例:生成16字节IV
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
不要使用math/rand,它不适用于安全场景。
常见问题与注意事项
- 密钥管理:密钥不应硬编码在代码中,建议通过环境变量或密钥管理系统加载
- IV不可重复:每次加密应使用不同的IV,但不需要保密
- 填充方式:CBC模式需要填充,PKCS7是标准做法
- 认证加密:若需防篡改,建议使用GCM模式(如
aes.NewGCM),它提供加密和完整性校验
GCM模式示例(推荐用于新项目)
GCM(Galois/Counter Mode)是一种AEAD(Authenticated Encryption with Associated Data)模式,更安全且无需手动处理填充。
func AESEncryptGCM(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
<pre class="brush:php;toolbar:false"><code>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
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil</code>}
func AESDecryptGCM(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)}
基本上就这些。掌握crypto/aes和cipher包的基本用法,能应对大多数加密需求。关键是选择合适的模式、正确处理密钥和随机数,并避免常见安全陷阱。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
-
505 收藏
-
503 收藏
-
502 收藏
-
502 收藏
-
502 收藏
-
346 收藏
-
391 收藏
-
385 收藏
-
386 收藏
-
226 收藏
-
291 收藏
-
344 收藏
-
399 收藏
-
348 收藏
-
438 收藏
-
129 收藏
-
327 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习