C#基于BouncyCastle使用OpenSSL生成的PEM私钥实现RSA解密遇类型转换异常
类型转换报错根因
你遇到的无法将RsaKeyParameters转换为AsymmetricCipherKeyPair异常,核心原因是:
OpenSSL 1.1.0及以上版本通过openssl genpkey生成的PEM私钥,默认输出PKCS#8编码格式(文件头为-----BEGIN PRIVATE KEY-----)。
旧示例代码默认假设PemReader读取私钥会返回AsymmetricCipherKeyPair对象,但BouncyCastle读取PKCS#8格式RSA私钥时,会直接返回RsaPrivateCrtKeyParameters类型实例,直接强转成AsymmetricCipherKeyPair必然触发类型转换错误。
可直接运行的修复实现
using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Encodings; using System; using System.Collections.Generic; using System.IO; using System.Text; static string RSADecryptWithOpenSSLKey(string base64CipherText, string pemPrivateKeyPath) { // 解码Base64格式密文 byte[] cipherBytes = Convert.FromBase64String(base64CipherText); // 读取PEM私钥 object pemLoadedObject; using (var fileReader = new StreamReader(pemPrivateKeyPath)) { var pemReader = new PemReader(fileReader); pemLoadedObject = pemReader.ReadObject(); } // 兼容不同PEM格式的私钥返回值,避免强制类型转换 RsaKeyParameters privateKey; if (pemLoadedObject is AsymmetricCipherKeyPair keyPair) { // 适配PKCS#1格式私钥(返回KeyPair的场景) privateKey = (RsaKeyParameters)keyPair.Private; } else if (pemLoadedObject is RsaPrivateCrtKeyParameters rsaPrivateKey) { // 适配PKCS#8格式私钥(genpkey生成的默认格式场景) privateKey = rsaPrivateKey; } else { throw new InvalidDataException("当前PEM文件不是有效的RSA私钥"); } // 匹配OpenSSL rsautl默认的PKCS#1 v1.5填充 var rsaEngine = new Pkcs1Encoding(new RsaEngine()); rsaEngine.Init(forEncryption: false, privateKey); // 按RSA块大小分块解密 int blockSize = rsaEngine.GetInputBlockSize(); List<byte> plainContent = new List<byte>(); for (int offset = 0; offset < cipherBytes.Length; offset += blockSize) { int readLength = Math.Min(blockSize, cipherBytes.Length - offset); plainContent.AddRange(rsaEngine.ProcessBlock(cipherBytes, offset, readLength)); } return Encoding.UTF8.GetString(plainContent.ToArray()); }
关键适配注意点
- 填充模式匹配:OpenSSL
rsautl -encrypt未显式指定-oaep参数时,默认使用PKCS#1 v1.5填充,必须对应代码中的Pkcs1Encoding;如果加密时启用了OAEP,再替换为OaepEncoding,否则即使密钥读取正常也会解密失败。 - 密文编码要求:OpenSSL命令行生成的密文是二进制格式,在C#中使用前需要先转换为Base64字符串,不能直接以文本方式读取二进制密文。
- 格式零适配:修复后的读取逻辑同时兼容PKCS#1、PKCS#8两种常见RSA PEM私钥格式,不需要手动用OpenSSL命令转换现有私钥的格式,直接使用原
genpkey生成的文件即可正常解析。
内容的提问来源于stack exchange,提问作者gmmo
相关产品推荐
相关产品推荐

