问题描述
我创建了一个自签名 PFX X509Certificate2(使用这个答案)但由于某种原因,证书的私钥正在抛出 NotSupportedException 与真正的 HasPrivateKey 属性无关.
I created a self signed PFX X509Certificate2 (using this answer) but for some reason, the private key of the certificate is throwing a NotSupportedException despiste a true HasPrivateKey property.
string password = "MyPassword";
ECDsa ecdsa = ECDsa.Create();
CertificateRequest certificateRequest = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256);
X509Certificate2 cert = certificateRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
File.WriteAllBytes("e:\\mycert.pfx", cert.Export(X509ContentType.Pfx, password));
//I tried to load the with every flag without success...
X509Certificate2 loadedCert = new X509Certificate2("e:\\mycert.pfx", password);
if (loadedCert.HasPrivateKey)
{
//loadedCert.HasPrivateKey is true but loadedCert.PrivateKey raise a NotSupportedException...
using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)loadedCert.PrivateKey)
{
byte[] encryptedBytes = rsa.Encrypt(Encoding.UTF8.GetBytes("Hello"), false);
byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, false);
string result = Encoding.UTF8.GetString(decryptedBytes);
}
}
有些人提到调用证书的导出会修复私钥,但它对我不起作用.我可能遗漏了一些东西,但我不知道它可能是什么.是不是某处缺少参数?
Some have mentioned that calling the Export of the certificate would fix the private key but it didn't work for me. I'm probably missing something but I can't figure what it could be. Is there a missing parameter somewhere?
推荐答案
您正在创建 ECDSA 密钥对,而 X509Certificate2.PrivateKey
仅支持存储在旧加密服务提供商中的 DSA 和 RSA 私钥(CSP).ECDSA 始终存储在此属性不支持的密钥存储提供程序 (KSP) 中.相反,您必须使用 GetECDsaPrivateKey
扩展方法:GetECDsa509CertificateKey(X509Certificates_X509Certificate2_)
You are creating ECDSA key pair, while X509Certificate2.PrivateKey
supports only DSA and RSA private keys that are stored in legacy cryptographic service provider (CSP). ECDSA is always stored in key storage provider (KSP) which is not supported by this property. Instead, you must use GetECDsaPrivateKey
extension method: GetECDsaPrivateKey(X509Certificate2)
这篇关于为什么自签名 PFX X509Certificate2 私钥会引发 NotSupportedException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!