Casting private key to RSACryptoServiceProvider not working

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


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
  //...
}