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

Golang crypto加密解密 AES/RSA实现

P粉602998670
发布: 2025-09-02 10:28:01
原创
261人浏览过
Go语言中通过crypto包实现AES和RSA加密解密:AES采用CBC模式配合PKCS7填充,需生成密钥和随机IV,加解密使用相同密钥;RSA采用PKCS1v15标准,公钥加密私钥解密,适用于小数据加密或密钥传输;实际应用中常结合二者优势,使用RSA加密AES密钥,AES加密主体数据,以兼顾性能与安全。

golang crypto加密解密 aes/rsa实现

在Go语言中实现加密和解密功能,常用的是标准库中的 crypto 包。AES 和 RSA 是两种主流加密算法:AES 属于对称加密,适合加密大量数据;RSA 属于非对称加密,适合密钥交换或数字签名。下面分别介绍如何在 Golang 中实现 AES 和 RSA 的加密解密。

AES 对称加密(CBC 模式)

AES 加密使用相同的密钥进行加密和解密。常见的模式有 CBC、GCM 等。这里以 CBC 模式为例,配合 PKCS7 填充。

示例:AES-CBC 加密解密

加密过程:

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

  • 生成密钥(16/24/32 字节,对应 AES-128/192/256)
  • 生成随机 IV(初始化向量,16 字节)
  • 对明文进行 PKCS7 填充
  • 使用 CBC 模式加密
  • 将 IV 和密文拼接返回

解密过程:

  • 从密文中提取 IV(前 16 字节)
  • 使用密钥和 IV 初始化解密器
  • 解密后去除 PKCS7 填充

代码实现:

package main
<p>import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
)</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;">// 填充明文(PKCS7)
blockSize := block.BlockSize()
padding := blockSize - len(plaintext)%blockSize
padtext := make([]byte, len(plaintext)+padding)
copy(padtext, plaintext)
for i := len(plaintext); i < len(padtext); i++ {
    padtext[i] = byte(padding)
}

ciphertext := make([]byte, aes.BlockSize+len(padtext))
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:], padtext)

return ciphertext, nil
登录后复制

}

知我AI
知我AI

一款多端AI知识助理,通过一键生成播客/视频/文档/网页文章摘要、思维导图,提高个人知识获取效率;自动存储知识,通过与知识库聊天,提高知识利用效率。

知我AI 101
查看详情 知我AI

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, err
}

iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]

if len(ciphertext)%aes.BlockSize != 0 {
    return nil, err
}

mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)

// 去除 PKCS7 填充
padding := int(ciphertext[len(ciphertext)-1])
if padding < 1 || padding > aes.BlockSize {
    padding = 0
}
plaintext := ciphertext[:len(ciphertext)-padding]

return plaintext, nil
登录后复制

}

RSA 非对称加密(PKCS1v15)

RSA 使用公钥加密,私钥解密。适合加密小数据(如 AES 密钥)。Go 中使用 crypto/rsacrypto/rand 实现。

生成密钥对(可保存为 PEM 文件)

生成 RSA 密钥:

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
)
<p>func GenerateRSAKey(bits int) (*rsa.PrivateKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, err
}
return privateKey, nil
}</p><p>func SavePrivateKeyToPEM(privateKey *rsa.PrivateKey, filename string) error {
encoded := x509.MarshalPKCS1PrivateKey(privateKey)
pemBlock := &pem.Block{
Type:  "RSA PRIVATE KEY",
Bytes: encoded,
}
// 写入文件
return nil // 省略文件写入逻辑
}</p><p>func SavePublicKeyToPEM(publicKey *rsa.PublicKey, filename string) error {
encoded, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
pemBlock := &pem.Block{
Type:  "PUBLIC KEY",
Bytes: encoded,
}
// 写入文件
return nil
}
登录后复制

RSA 加密与解密:

func RSAEncrypt(plaintext []byte, publicKey *rsa.PublicKey) ([]byte, error) {
    ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plaintext)
    if err != nil {
        return nil, err
    }
    return ciphertext, nil
}
<p>func RSADecrypt(ciphertext []byte, privateKey *rsa.PrivateKey) ([]byte, error) {
plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
if err != nil {
return nil, err
}
return plaintext, nil
}
登录后复制

实际使用建议

在实际应用中,通常结合 AES 和 RSA 使用:

  • 用 AES 加密大量数据(速度快)
  • 用 RSA 加密 AES 的密钥(安全传输
  • 接收方先用私钥解密出 AES 密钥,再用 AES 解密数据

这种混合加密方式兼顾性能和安全性。

注意事项

  • AES 密钥应为 16/24/32 字节,推荐使用 32 字节(AES-256)
  • IV 必须随机且唯一,不能重复使用
  • RSA 加密明文长度受限(如 2048 位 RSA 最多加密 245 字节)
  • 生产环境建议使用 RSA + OAEP 或 AES-GCM(更安全)
  • 密钥和私钥需妥善保管,避免硬编码

基本上就这些。Go 的 crypto 库设计清晰,只要理解加密流程,实现并不复杂,但细节容易出错,比如填充、IV 管理等,需格外注意。

以上就是Golang crypto加密解密 AES/RSA实现的详细内容,更多请关注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号