1

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

MarsRoverII
  • 111
  • 1
  • 15

1 Answers1

2

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);
Crypt32
  • 12,850
  • 2
  • 41
  • 70
  • True, but *sometimes* you really do want to export the private parameters/key. I'm glad you solved the OP's problem, but it would be nice if you'd tackled the root cause of *why* calling `GetRSAPrivateKey().ExportParameters(true)` was throwing. – Cocowalla Dec 10 '20 at 22:39
  • In a given case it was an XY problem, so don't need to solve irrelevant problems. If you have specific issue, start your own thread. – Crypt32 Dec 10 '20 at 23:12