为什么自签名PFX X509Certificate2私钥会引发NotSupportedException



我创建了一个自签名的PFX X509Certificate2(使用这个答案(,但由于某种原因,证书的私钥抛出了一个NotSupportedException,从而取消了一个真正的HasPrivateKey属性。

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);
}
}

有些人提到,调用证书导出会修复私钥,但对我来说不起作用。我可能丢失了一些东西,但我不知道它可能是什么。是否有丢失的参数?

您正在创建ECDSA密钥对,而X509Certificate2.PrivateKey仅支持存储在传统加密服务提供商(CSP(中的DSA和RSA私钥。ECDSA始终存储在密钥存储提供程序(KSP(中,此属性不支持该提供程序。相反,您必须使用GetECDsaPrivateKey扩展方法:GetECDsaPrivateKey(X509Certificate2(

公钥密码有两种类型的算法(RSA和ECC(。问题是你正在创建一个ECC(I.E ECDsa(,然后你试图将其作为RSA私钥。这肯定是不正确的。这里你应该做的是在两边都使用一个算法。2.如果您只想加密然后解密数据,为什么要使用X509Certificate2,请使用AES。这是为了这个目的。

最新更新