Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

BadPaddingException in AES

 
Nitin Dubey
Ranch Hand
Posts: 126
Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In which line does the exception occur?
 
Joe Ess
Bartender
Pie
Posts: 9258
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nitin Dubey
Ranch Hand
Posts: 126
Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 290
Java Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Aryan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic