首页 > 后端开发 > Golang > 正文

Golangcrypto包基础加密与解密方法

P粉602998670
发布: 2025-09-20 16:11:01
原创
973人浏览过
Go语言crypto包支持AES对称加密,推荐使用GCM模式。示例展示了CBC和GCM两种模式的加解密实现,强调密钥安全管理、IV随机生成及PKCS7填充处理,避免安全漏洞。

golangcrypto包基础加密与解密方法

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。

步骤说明:

立即学习go语言免费学习笔记(深入)”;

  • 生成密钥和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;"><pre class="brush:php;toolbar:false;">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
登录后复制

}

度加剪辑
度加剪辑

度加剪辑(原度咔剪辑),百度旗下AI创作工具

度加剪辑 63
查看详情 度加剪辑

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;"><pre class="brush:php;toolbar:false;">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
登录后复制

}

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
登录后复制
包的基本用法,能应对大多数加密需求。关键是选择合适的模式、正确处理密钥和随机数,并避免常见安全陷阱。

以上就是Golangcrypto包基础加密与解密方法的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号