在goframe框架中实现aes和rsa加解密,核心在于利用go标准库的`crypto/aes`和`crypto/rsa`包处理底层算法,并通过goframe提供的`ghttp`中间件或自定义handler进行请求拦截与响应封装。具体做法是定义一个包含公钥、私钥和aes密钥的结构体,编写独立的加密和解密函数,然后在路由注册时通过中间件对特定接口的请求参数进行解密,或对返回结果进行加密。这样做可以确保数据在传输过程中的机密性,同时保持业务逻辑层的简洁。

AES对称加密如何配置密钥并实现加解密
AES加密使用相同的密钥进行加密和解密,适合大数据量传输。在GoFrame中,通常将AES密钥硬编码在配置文件中或通过环境变量注入,并在初始化阶段加载。实现时,需先对明文进行PKCS7填充,然后使用AES-CBC模式进行加密,生成IV(初始向量)并与密文拼接传输;解密时则逆向操作,移除填充并还原明文。

package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
// AESKey 假设这是从配置中获取的32字节密钥
var AESKey = []byte("0123456789abcdef0123456789abcdef")
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS7Unpadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func AesEncrypt(plaintext string) (string, error) {
block, err := aes.NewCipher(AESKey)
if err != nil {
return "", err
}
plaintextBytes := []byte(plaintext)
padded := PKCS7Padding(plaintextBytes, block.BlockSize())
iv := make([]byte, block.BlockSize())
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(padded))
mode.CryptBlocks(crypted, padded)
// 返回 IV + 密文
result := append(iv, crypted...)
return fmt.Sprintf("%x", result), nil
}
func AesDecrypt(ciphertextHex string) (string, error) {
ciphertext, err := hex.DecodeString(ciphertextHex)
if err != nil {
return "", err
}
block, err := aes.NewCipher(AESKey)
if err != nil {
return "", err
}
iv := ciphertext[:aes.BlockSize]
crypted := ciphertext[aes.BlockSize:]
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(crypted, crypted)
unpadded := PKCS7Unpadding(crypted)
return string(unpadded), nil
}
上述代码展示了完整的AES-CBC加解密流程。注意在实际GoFrame应用中,应将`hex.EncodeToString`的结果直接作为API响应的一部分,或者在JSON结构中包含`iv`和`ciphertext`字段以便前端解析。密钥管理应严格遵循安全规范,避免硬编码在生产环境。
RSA非对称加密如何生成密钥对并实现加解密
RSA加密使用公钥加密、私钥解密,适合小数据量(如密钥交换)或数字签名场景。在GoFrame项目中,通常在服务启动时生成RSA密钥对,或将预生成的密钥文件加载到内存中。由于RSA加密有长度限制(取决于密钥长度,如2048位最多加密约245字节),实际应用中常采用“RSA加密AES密钥,AES加密数据”的混合加密模式。若仅演示纯RSA加解密,需确保明文长度不超过限制。

package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
)
var privateKey *rsa.PrivateKey
var publicKey *rsa.PublicKey
func InitRSA() error {
// 实际项目中应从文件或配置加载
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
privateKey = key
publicKey = &key.PublicKey
return nil
}
func RsaPublicEncrypt(plaintext string) (string, error) {
msg := []byte(plaintext)
ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, msg)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", ciphertext), nil
}
func RsaPrivateDecrypt(ciphertextHex string) (string, error) {
ciphertext, err := hex.DecodeString(ciphertextHex)
if err != nil {
return "", err
}
plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
if err != nil {
return "", err
}
return string(plaintext), nil
}
该段代码实现了基于PKCS#1 v1.5填充的RSA加解密。在GoFrame中,可将`RsaPublicEncrypt`的结果作为API的请求参数发送,后端使用`RsaPrivateDecrypt`还原。需注意,RSA运算开销较大,不应直接用于加密大量业务数据。建议结合AES使用:前端用RSA加密随机生成的AES密钥,再用AES加密业务数据,最后将两者一并提交。
如何在GoFrame中间件中自动解密请求参数
在GoFrame中,可以通过自定义中间件拦截特定路由的请求,自动对加密参数进行解密,从而让业务Handler接收到明文数据。具体做法是创建一个中间件函数,检查请求头或查询参数中是否包含加密标识,若有则调用解密函数处理,并将解密后的值写入上下文或替换原始参数。这种方式对业务代码透明,无需在每个Handler中重复编写解密逻辑。
package middleware
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"your_project/utils" // 假设加解密工具类在此路径
)
func DecryptMiddleware(r *ghttp.Request) {
// 示例:假设前端传递了 encrypted_data 字段
encryptedData := r.Get("encrypted_data").String()
if encryptedData == "" {
r.Middleware.Next()
return
}
// 执行AES解密
decrypted, err := utils.AesDecrypt(encryptedData)
if err != nil {
r.Response.WriteJson(g.Map{
"code": 500,
"message": "解密失败",
})
r.ExitAll()
return
}
// 将解密后的值覆盖原参数,供后续Handler使用
r.SetParam("data", decrypted)
r.Middleware.Next()
}
在路由注册时应用此中间件:g.Server().Group("/api", func(group *ghttp.RouterGroup) { group.Middleware(middleware.DecryptMiddleware); group.ALL("/submit", handler.Submit) })。这样,当客户端发送包含`encrypted_data`的请求时,中间件会自动解密并将其存入`data`参数,Handler只需读取`r.Get("data")`即可获取明文。这种设计保持了关注点分离,提升了代码可维护性。











