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 .

The encryption and decryption method did not appear in the window when testing the problem no matter what. put the encryption process On android. when decryption is posted to Linuxserver, Android will always fail when it uploads encrypted results to Linux, making it impossible for the user to log on successfully. After examination, after testing. Found that AES decryption failed on Linux and an error occurred:

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

Now come to think of their own solution:

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? But after the union, the binary is compared. Found no problem. So where is the problem?

Continue to tune, carefully compare 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. The approximate meaning is: the provided block of words does not meet the filling. What do you mean? Originally in the use of encryption, the last one is not long enough, it will take the initiative to make up, then in our byte array to string conversion process, can be filled with the invisible character changed. So the system throws an exception.

Problem found, how to solve it? The way for example is the following:

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;}}


Execution Result:


Put the encryption on the Android. After decrypting the amplification on Linux, for example the following:

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, the decryption end changes the decryption process. , the encryption process on the encryption side also changes. Whatever the case, the program has to be patient. With a thing, its simple main principle is still to know.





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.