Java AES encryption decryption on Windows test everything is OK, upload to space when decryption error occurs. Space is a Linux system
View Log Discovery This exception occurred
Javax.crypto.BadPaddingException:Given final block not properly padded
Baidu at the back of a bit finally solved, in the generation of key when the error occurred
The original code:
PrivateKey Initkeyforaes (String key)throwsnosuchalgorithmexception {if(NULL= = Key | | Key.length () = = 0) { Throw NewNullPointerException ("Key not is null"); } secretkeyspec Key2=NULL;Try{keygenerator KGen= Keygenerator.getinstance ("AES"); Kgen.init (128, New SecureRandom (Key.getbytes ())); Secretkey Secretkey=Kgen.generatekey (); byte[] Encodeformat =secretkey.getencoded (); Key2=NewSecretkeyspec (Encodeformat, "AES"); } Catch(NoSuchAlgorithmException ex) {Throw Newnosuchalgorithmexception (); } returnKey2; }
Mostly the red part of the problem
Modified code:
PrivateKey Initkeyforaes (String key)throwsnosuchalgorithmexception {if(NULL= = Key | | Key.length () = = 0) { Throw NewNullPointerException ("Key not is null"); } secretkeyspec Key2=NULL; securerandom Random = Securerandom.getinstance ("sha1prng"); Random.setseed (Key.getbytes ()); Try{keygenerator KGen= Keygenerator.getinstance ("AES"); Kgen.init (128, random); Secretkey Secretkey=Kgen.generatekey (); byte[] Encodeformat =secretkey.getencoded (); Key2=NewSecretkeyspec (Encodeformat, "AES"); } Catch(NoSuchAlgorithmException ex) {Throw Newnosuchalgorithmexception (); } returnKey2; }
In fact, SecureRandom created by different ways and caused by the error, the specific principle I do not understand, because the encryption and decryption code are online search, specifically did not study this. Anyway, it's good to solve the problem.
This is where I found the solution: http://wenku.baidu.com/link?url= Woibkheni2z5gfol5prjgbe8res1dzezlrvfy1ntl89qjwttwxunlmgexvywgbgxr25orvokpjti5m3o95kw0yihwgfvenjizt1-0yvrqua
Javax.crypto.BadPaddingException:Given final block not properly padded solution