Java Encryption issue
I am using PBE encryption t开发者_如何学Co 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
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.
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.
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.
精彩评论