Sensitive data in the interface API is returned after secure encryption based on AES

Source: Internet
Author: User
Tags md5 digest md5 hash

I haven't written a blog for a long time, and some are afraid to open the familiar editor.

Scenario: To encrypt an interface that involves sensitive data (account number, password) to return

Because there is no relevant experience, so first on the internet for a while, this blog good https://www.cnblogs.com/codeon/p/6123863.html gave me some ideas and inspiration.

Let's introduce two vague, easy-to-confuse concepts.

    • Base64 Code , look at the name can know this is a encoding, encoding method has a lot of ASCII, Unicode, UTF-8, etc., BASE64 encoding will be 3 bytes of binary data encoded into 4 bytes of text data, the length is increased to the original 4/3. It is important to emphasize that Base64 is not a cryptographic decryption algorithm in the security domain, although sometimes it is often seen that some blogs and transformation tools speak Base64 encryption and decryption. In fact, Base64 can only be regarded as a coding algorithm, the data content is encoded to fit the transmission. Although the original text also becomes a character format that cannot be seen after the Base64 encoding, this approach is very elementary and simple. the specific understanding of the individual coding scenarios can be referenced in this blog, 50993861.
    • MD5 Digest Algorithm , which is a hash function, extracts the characteristics of the data, the output is an irreversible hash value, used to represent a certain information a without exposing the content of information A, generally used in the digital signature scene.

The encryption method is determined: Finally, the sensitive plaintext information in my interface is encrypted by AES, and finally the ciphertext is returned to the client.

In some of the AES decryption examples on the web, there are many Javax.crypto.BadPaddingException:Given final block not properly padded issues in the AES decrypt step. And many of the answers are said to be specious, after my debugging and correction, the following code can normally complete the Aes/des encryption and decryption operations.

Package Com.test.utils;import Org.apache.logging.log4j.logmanager;import Org.apache.logging.log4j.logger;import Sun.misc.base64decoder;import Sun.misc.base64encoder;import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import Javax.crypto.Cipher;import Javax.crypto.secretkey;import Javax.crypto.secretkeyfactory;import Javax.crypto.spec.deskeyspec;import Javax.crypto.spec.ivparameterspec;import javax.crypto.spec.secretkeyspec;/** * @Author: LeeChao * @Date: 2018/7/5 * @ Describe: Cryptographic Tool class * @Modified by: */public class Encryptutil {public static final Logger Logger = Logmanager.getlogger (E    Ncryptutil.class);    The AES-128-CBC encryption mode is used here and the key needs to be 16 bits.    private static final String Aes_encrypt_mode = "aes/cbc/pkcs5padding";    16 fixed offset vector private static final String Iv_parameter = "1234567890abcdef";    Private final static String Des_encrypt_mode = "DES"; /** * AES Encryption * * @param aeskey encryption key can be composed of 26 letters and numbers, *@param content * @return * @throws Exception */public static string Aesencrypt (String Aeskey, String conte        NT) {//Initialize return results String result = NULL;            try {Cipher Cipher = cipher.getinstance (Aes_encrypt_mode);            Byte[] raw = aeskey.getbytes ();            Secretkeyspec Skeyspec = new Secretkeyspec (Raw, "AES");            With CBC mode, a vector IV is required to increase the strength of the cryptographic algorithm Ivparameterspec IV = new Ivparameterspec (Iv_parameter.getbytes ());            Cipher.init (Cipher.encrypt_mode, Skeyspec, iv);            Byte[] encrypted = cipher.dofinal (Content.getbytes ("Utf-8"));            Transcoding is done here using BASE64.            result = new Base64encoder (). Encode (encrypted);        Base64 the line break after encryption to remove result = Result.replaceall ("\\r\\n", ""). ReplaceAll ("\ R", ""). ReplaceAll ("\ n", "");        } catch (Exception e) {logger.error ("AES Encryption exception" + E);    } return result; }/** * AES decryption * * @param aeskey * @param content     * @return * @throws Exception */public static string Aesdecrypt (string Aeskey, string content) {/        /Initialize returns the result of String results = null;            try {byte[] raw = aeskey.getbytes ("ASCII");            Secretkeyspec Skeyspec = new Secretkeyspec (Raw, "AES");            Cipher Cipher = cipher.getinstance (Aes_encrypt_mode);            Ivparameterspec IV = new Ivparameterspec (Iv_parameter.getbytes ());            Cipher.init (Cipher.decrypt_mode, Skeyspec, iv); byte[] encrypted1 = new Base64decoder (). Decodebuffer (content);//First Use Base64 to decrypt byte[] original = cipher.dofinal (enc            RYPTED1);        result = new String (original, "Utf-8");        } catch (Exception e) {logger.error ("AES decryption exception" + E);    } return result; }/** * MD5 hash listed as 16-bit fixed-length output * * @param sourcestr * @return * */public static string MD5 (String sourcest        R) {String result16 = ""; try {messagedigest MD = MessagediGest.getinstance ("MD5");            Md.update (Sourcestr.getbytes ());            byte b[] = Md.digest ();            int i;            StringBuffer buf = new StringBuffer ("");                for (int offset = 0; offset < b.length; offset++) {i = B[offset];                if (i < 0) i + = 256;                if (I <) buf.append ("0");            Buf.append (integer.tohexstring (i));        }//32-bit intercept is 16-bit result16 = buf.tostring (). SUBSTRING (8, 24);        } catch (NoSuchAlgorithmException e) {logger.error (e);    } return result16; }/********************des encryption method ***********************/public static byte[] Desencrypt (byte[] src, byte[] key) throw        s Exception {//des algorithm requires a trustworthy random number source SecureRandom sr = new SecureRandom ();        Create Deskeyspec object from raw key data deskeyspec DKs = new Deskeyspec (key); Create a key factory and use it to convert the Deskeyspec into a Secretkey object SecretkeYfactory keyfactory = secretkeyfactory.getinstance (Des_encrypt_mode);        Secretkey SecureKey = Keyfactory.generatesecret (DKS);        The Cipher object actually completes the cryptographic operation Cipher Cipher = cipher.getinstance (Des_encrypt_mode);        Initialize the Cipher object with a key Cipher.init (Cipher.encrypt_mode, SecureKey, SR);    Formal execution of cryptographic operations return cipher.dofinal (SRC); }/** * @param password Password * @param key Encryption String * @return */public final static string Desencryp T (string password, string key) {try {return byte2string (Desencrypt (Password.getbytes (), Key.getbytes ()        ));    } catch (Exception e) {} return null;        } public static string byte2string (byte[] b) {string hs = "";        String stmp = "";            for (int n = 0; n < b.length; n++) {stmp = (java.lang.Integer.toHexString (b[n] & 0XFF));            if (stmp.length () = = 1) HS = HS + "0" + stmp; else HS = hs + stmp;       } return Hs.touppercase (); }/** * @param src data source * @param key key, length must be a multiple of 8 * @return * @throws Exception */public static Byte[] Desdecrypt (byte[] src, byte[] key) throws Exception {//des algorithm requires a trustworthy random number source SecureRandom sr = new Sec        Urerandom ();        Create a Deskeyspec object from the original key data deskeyspec DKs = new Deskeyspec (key); Create a key factory and use it to convert the Deskeyspec object to a Secretkey object secretkeyfactory keyfactory = Secretkeyfactory.getinstance (des_encryp        T_mode);        Secretkey SecureKey = Keyfactory.generatesecret (DKS);        The Cipher object actually completes the decryption operation Cipher Cipher = cipher.getinstance (Des_encrypt_mode);        Initialize the Cipher object with a key Cipher.init (Cipher.decrypt_mode, SecureKey, SR);    Formally perform decryption operation return cipher.dofinal (SRC); } public final static string Desdecrypt (string data, string key) {try {return new string (Desdecrypt        (String2byte (Data.getbytes ()), Key.getbytes ())); } catch (Exception e) {e.printstacktrace ();    } return null; } public static byte[] String2byte (byte[] b) {if ((b.length% 2)! = 0) throw new Illegalargumentexce        Ption ("Length is not even");        byte[] B2 = new BYTE[B.LENGTH/2];            for (int n = 0; n < b.length; n + = 2) {String item = new string (b, n, 2);        B2[N/2] = (byte) integer.parseint (item, 16);    } return B2; } private static string Testdecryptaes (string Authcode, String ciphertext) {System.out.println ("===============        ======aes decryption ===================== ");        String key = MD5 (Authcode);        MD5 hash lists the 16-bit fixed-length key System.out.println ("md5-16:" + key);        Long encrypttime = System.currenttimemillis ();        String destring = Aesdecrypt (key, ciphertext);        Long endTime = System.currenttimemillis ();        System.out.println ("Decryption Time:" + (Endtime-encrypttime) + "millisecond");        System.out.println ("Decrypted string is:" + destring); Return DestrinG         } public static void Main (string[] args) throws Exception {//code String Authcode = "8373964002824192"; Config_info String ciphertext = "IIK82BTFJLZUPT0GUVPZ6VX/ORFDCNHRVVJC4RHPJQZ15VFEVZV/TVOTNZYI3K6V2NHMLWP dhd4ylqw1e/wr78jdemif/ymsvr6cmu5utnrks0qgdooseprxd5t996tzxw18n/scsn++ h1sokdzs8hvei0tbp5z0p5wmqrvi6rq1badqcysbtgcg3lipy0yeo/fxufzzw6a5yj/ pruosgywyxhrwslabmbr1c3hpsxppxjkvql6qlkkt38z2wy4k3ag3+ii7e03kbvbbr/omz8nir7s7eqzhgfbglaznaba6ikah/ z6w2gtop4vnhpq2ncwcndodk8twr7bk3rd657rqyrj/c7ebtli+gpc8mtooorlow9iekrpb3pqkdk8r8awljzi0dzxwxuon+fngdosm51qn+ Ojbunga7minanki8bhhynv1mlbh0sdf4vusnwfjp1zblduu1dnuzbl7b2cwgasyxhc4y2lsonx8ddxgqxqxiv2n4jfjkgqbsj3sapik5wcteih8mjzygnxohd uspxunlpmvhsjp3xjlmtjexyimfqorl+gnbnwfucqhu+lqnusdx+ntqjaeq7cp+c9ythnujr8fslzsejnk2pjpikxupmnjm+ 3t8d7j7koyzoyrh5eymcl6h499lnywf//xax3rtufsihvvt7erjj2avu/0zpabv5x4llbjvrsojydzqiduyqph3chi+hwhjsbxw+        rzlttcoryv4fyxdm9/nepgfp3wwgxmnfwi5s/rfio4tserluuxtdza6fr9da== "; Decryption gets plaintext TeStdecryptaes (Authcode, ciphertext);        SYSTEM.OUT.PRINTLN ("=====================aes encryption =====================");        String key = MD5 ("8373964002824192");        MD5 hash lists the 16-bit fixed-length key System.out.println ("md5-16:" + key);        String CSRC = "123abctest" required to encrypt strings;        Encrypt long Lstart = System.currenttimemillis ();        String enstring = Aesencrypt (key, CSRC);        System.out.println ("Encrypted string is:" + enstring);        Long lusetime = System.currenttimemillis ()-Lstart;        SYSTEM.OUT.PRINTLN ("Encryption Time:" + Lusetime + "milliseconds");        Decrypt Lstart = System.currenttimemillis ();        String destring = Aesdecrypt (key, enstring);        System.out.println ("Decrypted string is:" + destring);        Lusetime = System.currenttimemillis ()-Lstart;        System.out.println ("Decryption time:" + Lusetime + "milliseconds");        SYSTEM.OUT.PRINTLN ("=====================des encryption =====================");        String password = "Test in English miscellaneous seven rotten eight mash @123654{";        String info = "123abctest"; Long Desstart = System.currenttimemillis ();        String encryptstring = desencrypt (info, password);        System.out.println (encryptstring);        System.out.println ("Des encryption time-consuming" + (System.currenttimemillis ()-Desstart) + "MS");        Desstart = System.currenttimemillis ();        String desencryptstring = desdecrypt (encryptstring, password);        System.out.println (desencryptstring);    System.out.println ("Des decryption time elapsed" + (System.currenttimemillis ()-Desstart) + "MS"); }}

  

Sensitive data in the interface API is returned after secure encryption based on AES

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.