Search code examples
c#rsax509certificate2cng

Getting RSA private key with .NET Core


On .NET Core (3.1), on both Windows and Linux platforms, I want to decrypt a message using the private keys of X509Certificiate2 instances. The certificates are retreived from certificate store on Windows platform, and from PFX file on Linux platforms respectively.

I wish to decrypt the message using something like:

static byte[] Decrypt(byte[] data, RSAParameters privateKey)
{
    using (var rsa = RSA.Create())
    {
        rsa.ImportParameters(privateKey);
        return rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA256);
    }
}

But when I try to extract the private key, I the an exception: "System.Security.Cryptography.CryptographicException: The requested operation is not supported."

var privateKey = x509cert.GetRSAPrivateKey();
var privateKeyParams = privateKey.ExportParameters(true); // <-- throws CryptographicException

What am I missing?


Solution

  • Change the signaure of your own Decrypt method to accept an instance of RSA class in the second parameter. You are doing some extra job by exporting private key into plaintext form and then import it to another object just to decrypt.

    var privateKey = x509cert.GetRSAPrivateKey();
    

    this line already returns an instance of RSA class. That is, all your code is simplified to:

    using (var rsa = x509cert.GetRSAPrivateKey())
    {
        return rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA256);
    }
    

    The exception is thrown because your private key is not exportable. And you don't really need to have exportable key.