将私钥转换为 RSACryptoServiceProvider 不起作用

Vin*_*ins 7 c# rsa private-key

我有一个 X509Certificate2 变量,我正在尝试将该变量的私钥转换为 RSACryptoServiceProvider

RSACryptoServiceProvider pkey = (RSACryptoServiceProvider)cert.PrivateKey;
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个例外。

System.InvalidCastException: '无法将类型为'System.Security.Cryptography.RSACng'的对象转换为类型'System.Security.Cryptography.RSACryptoServiceProvider'。'

发生这种情况很奇怪,因为 SO 中的其他答案提出了与我相同的程序,但我得到了一个例外。有什么解决办法吗?

Vin*_*ins 7

因此,经过几次尝试和评论中的讨论后,我想出了以下解决方案。

            RSA rsa = (RSA)cert.PrivateKey;
        (cert.PrivateKey as RSACng).Key.SetProperty(
            new CngProperty(
                "Export Policy",
                BitConverter.GetBytes((int)CngExportPolicies.AllowPlaintextExport),
                CngPropertyOptions.Persist));

        RSAParameters RSAParameters = rsa.ExportParameters(true);                      

        AsymmetricCipherKeyPair keypair = DotNetUtilities.GetRsaKeyPair(RSAParameters);
Run Code Online (Sandbox Code Playgroud)

问题是该变量rsa不可导出。为了改变这一点,我为导出策略设置了一个新的 CngProperty。现在完美运行

  • 您可能需要将 `(cert.PrivateKey as RSACng).Key` 设置为以 `(cert.PrivateKey is RSACng)` 为条件,就好像您确实获得了 RSACryptoServiceProvider(或 RSAOpenSsl)一样,这里会出现 NullPointerException . 但很高兴你让这个工作! (2认同)

Bra*_*ght 6

只是想注意,还有一个可以使用的扩展方法:

using System.Security.Cryptography.X509Certificates;

...

//certificate is a X509Certificate2
using (var rsa = certificate.GetRSAPrivateKey())
{
  //the var rsa is an RSA object
  //...
}
Run Code Online (Sandbox Code Playgroud)