views:

149

answers:

3

I am using PBE encryption to encrypt and decrypt some text on an Android application but I get the BadPaddingException: with the "pad block corrupted" message when I use the wrong private key to decrypt the text. My question, since I am not well versed with encryption in Java, is if this is the normal behavior of the encryption API, because I need to do some logic in the case when the wrong key is entered, but I do not know the private key, nor do I store it anywhere (storing just the encrypted and decrypted check text).

Thanks, Mihai

A: 

In short, yes, BadPaddingException is what you should expect if the wrong password/key was used during decryption.

Edit: But as others have pointed out, this isn't something you should communicate out of your decryption code. It's simply a way of knowing that an incorrect key was used.

Adrian
A: 

Yeah, less then ideal ( http://developer.android.com/reference/javax/crypto/BadPaddingException.html ). The decryption logic needs to strip the padding before it gets to the actual cypher-text and things go bad in that early stage.

David Soroko
+2  A: 

It is normal that most key mismatches result in a "bad padding error". But this is not 100% foolproof either. For instance, in the case of symmetric encryption with PKCS#5 padding (a very common way to pad data), about 0.4% of wrong keys will not result in a bad padding. The decrypted data will still be garbage, but, out of freak chance, that garbage turned out to end with a valid padding. Your application must not make it apparent whether a decryption failure is due to bad padding, or to garbage with freakishly valid padding: that information (whether the key is part of the 0.4% of keys which yield a proper padding) is a leak which can have severe consequences. There have been some attacks against SSL connections that way.

Thomas Pornin
Thanks for the information Thomas, so what this means is that if I want to check the validity of a private key I should handle the BadPaddingException as a proof that the private key is invalid, but also check if the result of the decryption is what is expected or just garbage that resulted from freakishly valid padding. This way, I can protect from situations when a key is invalid but check data gets decrypted.
r1k0
Yes. For a more complete treatment, consider adding a MAC (Message Authentication Code -- that's somewhat like a checksum with a key).
Thomas Pornin
Thanks Thomas, this seems to solve my problem.
r1k0