商城首页欢迎来到中国正版软件门户

您的位置:首页 >Golang AES RSA加密解密实现方法

Golang AES RSA加密解密实现方法

  发布于2025-10-03 阅读(0)

扫一扫,手机访问

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 加密解密

加密过程:

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

解密过程:

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

代码实现:

package main

import ( "crypto/aes" "crypto/cipher" "crypto/rand" "io" )

func AESEncrypt(plaintext []byte, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err }

// 填充明文(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

}

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"
)

func GenerateRSAKey(bits int) (*rsa.PrivateKey, error) { privateKey, err := rsa.GenerateKey(rand.Reader, bits) if err != nil { return nil, err } return privateKey, nil }

func SavePrivateKeyToPEM(privateKey *rsa.PrivateKey, filename string) error { encoded := x509.MarshalPKCS1PrivateKey(privateKey) pemBlock := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: encoded, } // 写入文件 return nil // 省略文件写入逻辑 }

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
}

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 管理等,需格外注意。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注