Two Laptop Bag
The moose likes Security and the fly likes BadPaddingException in AES Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » Security
Bookmark "BadPaddingException in AES" Watch "BadPaddingException in AES" New topic

BadPaddingException in AES

Nitin Dubey
Ranch Hand

Joined: Oct 30, 2000
Posts: 126

Guys, I am new to crypto world. I need to encrypt some numbers to a String and then from String back to the same number. Hence, I grabbed the following code from net did some modifications and trying to run but this is throwing exception.

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
In which line does the exception occur?
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

That code looks familiar. I just worked through a similar example. It turns out that you get the "bad padding exception" for one of two reasons. One, if your data is not the correct size for the encryption algorithm (this is fixed by "padding" the data to get the correct size). The other reason is if you attempt to use different keys to encrypt and decrypt the data.
Notice that your code generates a new key in the static block each time it runs. This is why the commented code works. It is using the same instance of skeySpec to encrypt and decrypt. If you take the encoded data from one run and try to decrypt it in another, this code generates a new skeySpec and you get an exception.

[How To Ask Questions On JavaRanch]
Nitin Dubey
Ranch Hand

Joined: Oct 30, 2000
Posts: 126

Thanks for the help Joe. I will be using this in a web application, I am planning to put this in startup and serialize the seckey so that it can be retrieved again. This is coz in our application the users will have the URL's all the time even if the server is down.

I hope this will work.
Aryan Khan
Ranch Hand

Joined: Sep 12, 2004
Posts: 290

Do not use Strings...You will run into trouble even if it works for some encrypted messages.
Always use base46 encoding.
Encode your string into base64 encrypt it, decrypt it and decode to string.


I agree. Here's the link:
subject: BadPaddingException in AES
It's not a secret anymore!