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 中的其他答案提出了与我相同的程序,但我得到了一个例外。有什么解决办法吗?
因此,经过几次尝试和评论中的讨论后,我想出了以下解决方案。
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。现在完美运行
只是想注意,还有一个可以使用的扩展方法:
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)