无法将私钥强制转换为RSACryptoServiceProvider [英] Casting private key to RSACryptoServiceProvider not working

查看:82
本文介绍了无法将私钥强制转换为RSACryptoServiceProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a X509Certificate2 variable and I'm trying to cast the private key of the variable to a RSACryptoServiceProvider

RSACryptoServiceProvider pkey = (RSACryptoServiceProvider)cert.PrivateKey;

但是我得到这个例外.

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

System.InvalidCastException: 'Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.'

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

It's weird that this happens because other answers in SO suggested the same procedure as mine but I get an exception. Any solutions to this?

推荐答案

因此,在进行了几次尝试和评论后,我提出了以下解决方案.

So after a few tries and discussions in the comments I came up with the following solution.

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

问题是变量 rsa 无法导出.要更改此设置,我为导出策略设置了一个新的CngProperty.现在可以正常运行

The problem was that the variable rsa wasn't exportable. To change this I set a new CngProperty for the export policy. Works perfectly now

这篇关于无法将私钥强制转换为RSACryptoServiceProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆