1

I have the following implementation for decrypting a value. This implementation works, but in some small case the values I'm attempting to decrypt are throwing a Cryptographic Exception, with the message 'The Parameter is incorrect'. This occurs where I call the Decrypt method on the private key below.

All values are encrypted with the public key, base64 encoded in transit, and passed along to this method the same way, so I don't understand why it would be blowing up sometimes. If I re-encrypt with the public key, that new value can usually be unencrypted successfully.

Certificate in this case below is the X509Certificate2

public string Decrypt(CertificateType certificateType, byte[] encryptedString)
{
    string result = null;

    var certificate = GetCertificate(certificateType);

    var privateKey = certificate?.GetRSAPrivateKey();

    if (privateKey != null)
    {
        var decryptedBytes = privateKey.Decrypt(encryptedString, RSAEncryptionPadding.Pkcs1);

        result = Encoding.Default.GetString(decryptedBytes);
    }

    return result;
}

Any ideas as to what would cause that exception?

tdebruin
  • 33
  • 3

2 Answers2

2

You should run it 1000x and log all the errors, see what those base64 input strings have in common and what the passing ones do - my guess is that it's padding related with the base64 encoding (Some encoders will pad with equal signs at the end of the strings and some won't, then some decoders expect the padding and some are able to handle it). When it lines up right, the decrypt works, when it doesn't (the length of the base64 string) the method throws an exception. Other alternative is that instead of base64, you should be doing base64url encoding. When it works, it's because base64(x) == base64url(x) and when it doesn't it's because base64(x) != base64url(x)

Matt
  • 25,943
  • 66
  • 198
  • 303
0

Looks like it is with the Base64 encoding. Thank you for the help!

The Answer on this post did remove the decrypt issue I was having: RSA Encryption and Decryption successed in JS, but Decryption fails in C#

tdebruin
  • 33
  • 3