.NET Core加载X509证书报错,需从RSA公钥生成证书
.NET Core中加载RSA公钥替代X509证书的解决方案
问题场景
最初尝试通过以下代码加载证书:
var bytes = File.ReadAllBytes(certificatePath); var cert = new X509Certificate2(bytes);
抛出错误:
Cannot find the requested object
改用Import方法后:
var cert = new X509Certificate2(); cert.Import(_path);
抛出异常:
System.PlatformNotSupportedException : X509Certificate is immutable on this platform. Use the equivalent constructor instead.
补充信息
- 文件路径:
C:\XYZ\Documents\XYZ\rsakey.txt - 加密配置:RSA加密,ECB模式,PKCS1Padding填充,密钥长度1024
- 实际情况:传入的是RSA公钥文件,而非标准X509证书
解决方案
无需生成X509证书,直接加载RSA公钥即可,步骤如下:
1. 清理公钥格式
读取公钥文件内容后,去除多余的格式标识和换行符:
string publicKeyText = File.ReadAllText("C:\\XYZ\\Documents\\XYZ\\rsakey.txt"); // 清理PEM格式的头、尾及换行 publicKeyText = publicKeyText.Replace("-----BEGIN PUBLIC KEY-----", "") .Replace("-----END PUBLIC KEY-----", "") .Replace("\r", "") .Replace("\n", "");
2. 加载公钥到RSA实例
将清理后的Base64字符串转换为字节数组,导入到RSA对象:
using RSA rsa = RSA.Create(); byte[] publicKeyBytes = Convert.FromBase64String(publicKeyText); rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);
3. 执行RSA加密
按照指定的加密配置完成加密操作:
byte[] rawData = Encoding.UTF8.GetBytes("待加密内容"); byte[] encryptedData = rsa.Encrypt(rawData, RSAEncryptionPadding.Pkcs1);
内容的提问来源于stack exchange,提问作者Simone Spagna
相关产品推荐
相关产品推荐

