简体   繁体   English

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

[英]Why does self signed PFX X509Certificate2 private key raise a NotSupportedException?

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.我创建了一个自签名 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);
    }
}

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?某处是否缺少参数?

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 密钥对,而X509Certificate2.PrivateKey仅支持存储在传统加密服务提供商 (CSP) 中的 DSA 和 RSA 私钥。 ECDSA is always stored in key storage provider (KSP) which is not supported by this property. ECDSA 始终存储在此属性不支持的密钥存储提供程序 (KSP) 中。 Instead, you must use GetECDsaPrivateKey extension method: GetECDsaPrivateKey(X509Certificate2)相反,您必须使用GetECDsaPrivateKey扩展方法: GetECDsaPrivateKey(X509Certificate2)

there are two types of algorithms for public-key cryptography(RSA and ECC).公钥密码学有两种类型的算法(RSA和ECC)。 the problem is you are creating an ECC (IE ECDsa) and then you are trying to get it as an RSA private key.问题是您正在创建一个 ECC (IE ECDsa),然后您试图将其作为 RSA 私钥。 which is definitely not correct.这绝对是不正确的。 what you should do here is to use one algorithm on both sides so.你应该在这里做的是在两边都使用一种算法。 2. if you only want to Encrypt and then Decrypt piece of data, why using X509Certificate2 , use AES instead. 2.如果你只想加密然后解密一段数据,为什么要使用X509Certificate2 ,使用 AES 代替。 which is meant for this purpose.这是为此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM