While decrypting text using RSACryptoServiceProvider.Decrypt
, I am getting the error:
Error occurred while decoding OAEP padding.
This error normally indicates you are using a public key to decrypt, while you should be using a private key for decryption. Give it a try.
I ran into this exact problem. UnicodeEncoding.GetBytes
is not always the inverse of UnicodeEncoding.GetString
.
byte[] a = new byte[32];
RandomNumberGenerator gen = new RNGCryptoServiceProvider();
gen.GetBytes(a);
UnicodeEncoding byteConverter = new UnicodeEncoding();
byte[] b = byteConverter.GetBytes(byteConverter.GetString(a));
//byte array 'a' and byte array 'b' will not always contain the same elements.
This is why RSACryptoServiceProvider.Decrypt
fails. A lot of encrypt/decrypt examples on the web use Unicode encoding. Do not use Unicode encoding. Use Convert.FromBase64String
and Convert.ToBase64String
instead.
We were getting this issue when we were using the wrong key for decryption.
In my case the error has been caused by wrong padding settings.
Error: RSA decrypt: error:0407A079:rsa routines:RSA_padding_check_PKCS1_OAEP:oaep decoding error
I had openssl_public_encrypt()
with OPENSSL_PKCS1_PADDING
as a default value in PHP and keypair.decrypt()
with the default value RSA_PKCS1_OAEP_PADDING
in node-rsa.
So don't forget to check these options too.
Another thing to check: it was giving me this error, on the decrypt operation, as a result of forgetting to pass the public key into the RSACryptoServiceProvider
for the encrypt operation.
FYI, you can still be (en/de)crypting in the right key sequence (encr:pub key, decr:priv key) - i.e. can still get this error decrypting with a private key - it just may be the wrong private key (i.e. from another cert/key pair), not the one paired w/ the pub key with which u encrypted initially. If u turn off OAEP padding and get a "bad data" exception, that's another indication.