Resolves AES decryption failure under Linux

Source: Internet
Author: User
Tags array to string decrypt stringbuffer

Some time ago, with a AES encryption and decryption method, see the previous blog AES encryption and decryption . encryption and decryption method on the window to test the time there is no problem, the encryption process on the Android, Decryption published to the Linux server, when the encrypted results of Android to the Linux decryption is always failed, To allow the user to successfully log on, after inspection, after testing, found that AES decryption failed on Linux, an error occurred:

Javax.crypto.BadPaddingException:Given final block not properly padded

Now to review their own solutions:

Encryption process is on the Android, decryption is on the Linu, is not because of the environment, the encryption process generated in the binary and in the decryption process produced by the binary is different? However, after the joint adjustment, compared to the binary, found no problem. So where is the problem?

Continuing the tune-up, carefully compared to the results of each step in the encryption and decryption process, found the problem:

Linux decryption end:

Found here the cipher under the FirstService is worth.


Android Encrypted side:

found here the cipher under the FirstService is no value.


Baidu found after:

The only difference between encryption and decryption methods is that the schema of the cipher object is different, which excludes the possibility of the program being written incorrectly. Because the error message appears in Yichang, its approximate meaning is: the word block provided does not meet the filling. What do you mean? Originally in the use of encryption, the last one is not long enough, it will automatically make up, then in our byte array to string conversion process, it can be filled with the invisible character changes, so the system throws an exception.

Problem found, how to solve it? Here's how:

Package Ict.base.rest.services.app;import Java.io.unsupportedencodingexception;import Java.security.invalidkeyexception;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import Javax.crypto.badpaddingexception;import Javax.crypto.cipher;import Javax.crypto.illegalblocksizeexception;import Javax.crypto.keygenerator;import Javax.crypto.nosuchpaddingexception;import Javax.crypto.secretkey;import Javax.crypto.spec.IvParameterSpec; Import Javax.crypto.spec.secretkeyspec;public class Aesdecodeutils {public static void main (string[] args) {String Content = "G25"; String pwd = "8182838485"; String addpwd = "123456";//Encryption System.out.println ("Content before encryption:" + content); byte[] Enaccount = Encrypt (content, addpwd); byte[] Enpwd = Encrypt (pwd, addpwd); String encryptresultstr = Parsebyte2hexstr (Enaccount); String parsebyte2hexstr2 = Parsebyte2hexstr (ENPWD); System.out.println ("Post-encryption content:" + encryptresultstr);//decryption--account/Social Security Number byte[] Accountfrom = Aesdecodeutils.parsehexstr2byte (ENCRYPTRESULTSTR); byte[] Deaccount = Aesdecodeutils.decrypt (Accountfrom, addpwd); String useraccount = new string (deaccount); System.out.println ("Post-decryption content:" + useraccount);//decryption--password byte[] Pwdfrom = Aesdecodeutils.parsehexstr2byte ( PARSEBYTE2HEXSTR2); byte[] deuserpwd = Aesdecodeutils.decrypt (Pwdfrom, addpwd); String userpwd = new string (deuserpwd);//System.out.println (USERPWD);} /** * AES Encryption * * @param content * contents to encrypt * @param password * encryption using key * @return encrypted byte array */public STA Tic byte[] Encrypt (string content, string password) {SecureRandom random = null;try {<span style= "color: #ff0000;" >random = Securerandom.getinstance ("sha1prng"); Random.setseed (Password.getbytes ()); </span>} catch ( NoSuchAlgorithmException E1) {e1.printstacktrace ();} try {keygenerator KGen = keygenerator.getinstance ("AES");//Kgen.init (+, New SecureRandom (Password.getbytes ())); <span style= "color: #ff0000;" >kgen.init (n, random); </span>secretkey Secretkey = Kgen.generatekey ();byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key = new Secretkeyspec (Encodeformat, "AES"); Cipher Cipher = cipher.getinstance ("AES");//Create cipher byte[] bytecontent = content.getbytes ("Utf-8"); Cipher.init ( Cipher.encrypt_mode, key);//Initialize byte[] result = cipher.dofinal (bytecontent); return result; Encryption} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} catch (Nosuchpaddingexception e) {e.printstacktrace ();} catch (InvalidKeyException e) {e.printstacktrace ();} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch (Illegalblocksizeexception e) {e.printstacktrace ();} catch (Badpaddingexception e) {e.printstacktrace ();} return null;} /** * Converts binary to 16 binary encryption * * @param buf * @return */public static String parsebyte2hexstr (byte buf[]) {StringBuffer SB = new StringBuffer (); for (int i = 0; i < buf.length; i++) {String hex = integer.tohexstring (Buf[i] & 0xFF); if (hex.length () = = 1) {hex = ' 0 ' + hex;} Sb.append (Hex.touppercase ());} return sb.tostring ();} /** * Decryption * * @param content * To decrypt contents * @param password * Decryption key * @return */public static byte[] Decrypt (byte[] Con Tent, String password) {securerandom random = null;try {<span style= "color: #ff0000;" >random = Securerandom.getinstance ("sha1prng"); Random.setseed (Password.getbytes ()); </span>} catch ( NoSuchAlgorithmException E1) {e1.printstacktrace ();} try {keygenerator KGen = keygenerator.getinstance ("AES");//Kgen.init (+, New SecureRandom (Password.getbytes ())); <span style= "color: #ff0000;" >kgen.init (n, random); </span>secretkey Secretkey = Kgen.generatekey (); byte[] Encodeformat = Secretkey.getencoded (); Secretkeyspec key = new Secretkeyspec (Encodeformat, "AES"); Cipher Cipher = cipher.getinstance ("AES");//Create cipher Cipher.init (Cipher.decrypt_mode, key);//Initialize byte[] result = Cipher.dofinal (content); return result; Encryption} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} catch (Nosuchpaddingexception e) {e.printstacktrace ();} catch (InvalidKeyException e) {E.printstacktrace ();} catch (Illegalblocksizeexception e) {e.printstacktrace ();} catch (Badpaddingexception e) {e.printstacktrace ();} return null;}  /** * Convert 16 binary to binary * * @param hexstr * @return */public static byte[] Parsehexstr2byte (String hexstr) {if (Hexstr.length () < 1) return null;byte[] result = new Byte[hexstr.length ()/2];for (int i = 0; i < hexstr.length ()/2; i++) {int hi  GH = Integer.parseint (hexstr.substring (i * 2, I * 2 + 1), int low = Integer.parseint (Hexstr.substring (i * 2 + 1, I * 2 + 2), result[i] = (byte) (high * + low);} return result;}}


Operation Result:


After placing the encryption on the Android, decrypt and enlarge Linux, as follows:

At this point the firstservice is no longer null and has a value of cipher

Android Encrypted side:

Linux decryption end:


Summarize:

AES is symmetric encryption, decryption end to change the decryption process, the same encryption side of the encryption process will change, no matter how, tune the program is to have patience, with a thing, its simple basic principle or to know.





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Resolves AES decryption failure under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.