Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting private key to RSACryptoServiceProvider not working

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;

However I get this exception.

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

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?

like image 725
Vins Avatar asked May 02 '19 09:05

Vins


2 Answers

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

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

like image 69
Vins Avatar answered Oct 13 '22 12:10

Vins


Just wanted to note that there's also an extension method that can be used:

using System.Security.Cryptography.X509Certificates;

...

//certificate is a X509Certificate2
using (var rsa = certificate.GetRSAPrivateKey())
{
  //the var rsa is an RSA object
  //...
}
like image 5
Brad Albright Avatar answered Oct 13 '22 12:10

Brad Albright