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

.NET 3.5中PKCS8 PEM私钥转RSAParameter报错求助

解决PKCS8 PEM私钥转RSA密钥(.NET 3.5)

问题原因

PKCS8格式的RSA私钥通过PemReader读取后,返回的直接是RsaPrivateCrtKeyParameters类型对象,而非PKCS1格式对应的AsymmetricCipherKeyPair。你之前的代码错误地尝试将其强制转换为AsymmetricCipherKeyPair,导致抛出InvalidCastException。

修正后的代码

直接判断读取到的密钥类型,跳过对AsymmetricCipherKeyPair的拆包操作:

using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.IO;
using System.Security.Cryptography;

public RSACryptoServiceProvider ConvertPkcs8PemToRsa(string pem, bool isPrivate)
{
    PemReader pemReader = new PemReader(new StringReader(pem));
    object key = pemReader.ReadObject();
    
    RSAParameters rsaParameters;
    if (isPrivate)
    {
        // PKCS8私钥直接转为RsaPrivateCrtKeyParameters
        RsaPrivateCrtKeyParameters privateKeyParams = (RsaPrivateCrtKeyParameters)key;
        rsaParameters = DotNetUtilities.ToRSAParameters(privateKeyParams);
    }
    else
    {
        // 公钥处理(如果需要的话)
        RsaKeyParameters publicKeyParams = (RsaKeyParameters)key;
        rsaParameters = DotNetUtilities.ToRSAParameters(publicKeyParams);
    }
    
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.ImportParameters(rsaParameters);
    
    return rsa;
}

注意事项

  • 确保项目已正确引用BouncyCastle的.NET 3.5兼容版本(如BouncyCastle.Crypto.dll),建议使用1.8.5及以上的稳定版。
  • 生成JWT时,可使用RSACryptoServiceProvider配合适配.NET3.5的JWT库完成签名操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:20:56