Search code examples
rsax509certificate2encryption-asymmetric.net-core-3.1windows-10-desktop

Self Signed RSA Certificate export private key parameters exception in .NET Core 3.1 [Windows 10 Pro OS]


I have created a self signed RSA certificate and stored the Private key as .pfx file. Then from my .Net Core 3.1 code i'm trying to instantiate the X509Certificate2 object with the .pfx file. The X509Certificate2 instance is created successfully but from the code "certificate2.GetRSAPrivateKey().ExportParameters(true)" getting an exception as "The requested operation is not supported".

X509Certificate2 certificate2 = new X509Certificate2(privateKeyData, _privateKeyPwd, X509KeyStorageFlags.Exportable);
RSAParameters rSAParameters = certificate2.GetRSAPrivateKey().ExportParameters(true);

Exception: Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: 'The requested operation is not supported'.

Can you please help me.

Edit: The rSAParameters will be used to decrypt an encrypted symmetric key.

rsaProvider.ImportParameters(rSAParameters);
byte[] encryptedSymmetricKey = Convert.FromBase64String(dataKey);
// Decrypt using OAEP padding.
byte[] decryptedSymmetricKey = rsaProvider.Decrypt(encryptedSymmetricKey, fOAEP: true);


Solution

  • When I see something like rsaKey.ExportParameters(true), in 99.999% cases this indicates a bad design/patern in code.

    In fact, you don't need to export and re-import parameters, do it simply:

    X509Certificate2 certificate2 = new X509Certificate2(privateKeyData, _privateKeyPwd, X509KeyStorageFlags.Exportable);
    RSA privateKey = certificate2.GetRSAPrivateKey();
    // decrypt data
    byte[] decryptedSymmetricKey = privateKey.Decrypt(encryptedSymmetricKey, RSAEncryptionPadding.OaepSHA1);