You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go解密PHP openssl_public_encrypt PKCS#1 v1.5加密字符串问题排查

问题原因及修复方案
  • 解密算法不匹配:你当前使用的rsa.DecryptOAEP是针对OAEP填充的解密方法,但PHP侧openssl_public_encrypt指定的是PKCS#1 v1.5填充,两种填充规则完全不兼容,需改用rsa.DecryptPKCS1v15方法。
  • 缺少Base64解码步骤:你存储的加密字符串是Base64编码后的结果,PHP和Bash实现中都先执行了Base64解码操作,Go侧直接传入原始编码字符串会因密文格式错误导致解密失败。

修正后代码示例

import (
    "crypto/rsa"
    "encoding/base64"
    "errors"
    "crypto/x509"
    "encoding/pem"
)

func DecryptString(privKey *rsa.PrivateKey, encryptedBase64Str string) ([]byte, error) {
    // 先对输入的加密字符串做Base64解码
    encryptedBytes, err := base64.StdEncoding.DecodeString(encryptedBase64Str)
    if err != nil {
        return nil, err
    }
    // 使用PKCS#1 v1.5填充对应的解密方法
    decryptedBytes, err := rsa.DecryptPKCS1v15(nil, privKey, encryptedBytes)
    if err != nil {
        return nil, err
    }
    return decryptedBytes, nil
}

func GetPrivateKey() (*rsa.PrivateKey, error) {
    pemString := `******************`
    block, rest := pem.Decode([]byte(pemString))
    if block == nil || len(rest) > 0 {
        return nil, errors.New("invalid private key PEM format")
    }
    parseResult, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    key, ok := parseResult.(*rsa.PrivateKey)
    if !ok {
        return nil, errors.New("private key is not RSA type")
    }
    return key, nil
}

内容的提问来源于stack exchange,提问作者czende

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:45:04