Java code implementation: AES Encryption

Source: Internet
Author: User
Tags base64 decrypt


AES Encryption



AES is a reversible encryption algorithm that encrypts the user's sensitive information.



This article does not delve into the AES principle, only focus on Java code implementation of AES plus decryption.



Java Code Implementation



Recommended encryption password is 16-bit, to avoid the number of password less than 0, resulting in inconsistent passwords, plus decryption error.



iOS can set any length of encryption password, Java only support 16-bit /24-bit/32-bit, do not know whether to achieve any length, look big guy told.


package cn.roylion.common.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/ **
 * @Author: Roylion
 * @Description: AES algorithm package
 * @Date: Created in 9:46 2018/8/9
 * /
public class EncryptUtil {

    / **
     * Encryption Algorithm
     * /
    private static final String ENCRY_ALGORITHM = "AES";

    / **
     * Encryption algorithm / encryption mode / fill type
     * This example uses AES encryption, ECB encryption mode, and PKCS5Padding padding
     * /
    private static final String CIPHER_MODE = "AES / ECB / PKCS5Padding";

    / **
     * Set iv offset
     * This example uses ECB encryption mode, no need to set iv offset
     * /
    private static final String IV_ = null;

    / **
     * Set encrypted character set
     * This example uses UTF-8 character set
     * /
    private static final String CHARACTER = "UTF-8";

    / **
     * Set the encryption password processing length.
     * Add 0 if less than this length;
     * /
    private static final int PWD_SIZE = 16;

    / **
     * Password processing method
     * If encryption and decryption fail,
     * Please check this method first, to exclude the password length is not enough "0", resulting in inconsistent password
     * @param password pending password
     * @return
     * @throws UnsupportedEncodingException
     * /
    private static byte [] pwdHandler (String password) throws UnsupportedEncodingException {
        byte [] data = null;
        if (password == null) {
            password = "";
        }
        StringBuffer sb = new StringBuffer (PWD_SIZE);
        sb.append (password);
        while (sb.length () <PWD_SIZE) {
            sb.append ("0");
        }
        if (sb.length ()> PWD_SIZE) {
            sb.setLength (PWD_SIZE);
        }

        data = sb.toString (). getBytes ("UTF-8");

        return data;
    }

    // ========================> original encryption

    / **
     * Raw encryption
     * @param clearTextBytes plaintext byte array, byte array to be encrypted
     * @param pwdBytes encrypted password byte array
     * @return returns the encrypted ciphertext byte array, and the encryption error returns null
     * /
    public static byte [] encrypt (byte [] clearTextBytes, byte [] pwdBytes) {
        try {
            // 1 get the encryption key
            SecretKeySpec keySpec = new SecretKeySpec (pwdBytes, ENCRY_ALGORITHM);

            // 2 get Cipher instance
            Cipher cipher = Cipher.getInstance (CIPHER_MODE);

            // View the number of data blocks. The default is 16 (byte) * 8 = 128 bit
// System.out.println ("Number of data blocks (byte):" + cipher.getBlockSize ());

            // 3 Initialize the Cipher instance. Set execution mode and encryption key
            cipher.init (Cipher.ENCRYPT_MODE, keySpec);

            // 4 execute
            byte [] cipherTextBytes = cipher.doFinal (clearTextBytes);

            // 5 returns the ciphertext character set
            return cipherTextBytes;

        } catch (NoSuchPaddingException e) {
            e.printStackTrace ();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace ();
        } catch (BadPaddingException e) {
            e.printStackTrace ();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace ();
        } catch (InvalidKeyException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return null;
    }

    / **
     * Original decryption
     * @param cipherTextBytes ciphertext byte array, byte array to be decrypted
     * @param pwdBytes decrypt password byte array
     * @return returns the plaintext byte array after decryption, or null if decryption error
     * /
    public static byte [] decrypt (byte [] cipherTextBytes, byte [] pwdBytes) {

        try {
            // 1 get the decryption key
            SecretKeySpec keySpec = new SecretKeySpec (pwdBytes, ENCRY_ALGORITHM);

            // 2 get Cipher instance
            Cipher cipher = Cipher.getInstance (CIPHER_MODE);

            // View the number of data blocks. The default is 16 (byte) * 8 = 128 bit
// System.out.println ("Number of data blocks (byte):" + cipher.getBlockSize ());

            // 3 Initialize the Cipher instance. Set execution mode and encryption key
            cipher.init (Cipher.DECRYPT_MODE, keySpec);

            // 4 execute
            byte [] clearTextBytes = cipher.doFinal (cipherTextBytes);

            // 5 returns the plaintext character set
            return clearTextBytes;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace ();
        } catch (InvalidKeyException e) {
            e.printStackTrace ();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace ();
        } catch (BadPaddingException e) {
            e.printStackTrace ();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        // decryption error returns null
        return null;
    }

    // ========================> BASE64 <========================

    / **
     * BASE64 encryption
     * @param clearText, the text to be encrypted
     * @param password password, encrypted password
     * @return returns the ciphertext, the content obtained after encryption. Encryption error returns null
     * /
    public static String encryptBase64 (String clearText, String password) {
        try {
            // 1 Get the encrypted ciphertext byte array
            byte [] cipherTextBytes = encrypt (clearText.getBytes (CHARACTER), pwdHandler (password));

            // 2 Perform BASE64 encoder on the ciphertext byte array to get the ciphertext output by BASE6
            BASE64Encoder base64Encoder = new BASE64Encoder ();
            String cipherText = base64Encoder.encode (cipherTextBytes);

            // 3 returns the ciphertext output by BASE64
            return cipherText;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        // encryption error returns null
        return null;
    }

    / **
     * BASE64 decryption
     * @param cipherText ciphertext with decrypted content
     * @param password password, decrypted password
     * @return returns the plaintext, decrypted content. Decryption error returns null
     * /
    public static String decryptBase64 (String cipherText, String password) {
        try {
            // 1 Perform BASE64 decodebuffer on the ciphertext output by BASE64 to get the ciphertext byte array
            BASE64Decoder base64Decoder = new BASE64Decoder ();
            byte [] cipherTextBytes = base64Decoder.decodeBuffer (cipherText);

            // 2 decrypt the ciphertext byte array to get the plaintext byte array
            byte [] clearTextBytes = decrypt (cipherTextBytes, pwdHandler (password));

            // 3 Transcode according to CHARACTER, return plain text string
            return new String (clearTextBytes, CHARACTER);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        // decryption error returns null
        return null;
    }

    // ========================> HEX <========================

    / **
     * HEX encryption
     * @param clearText, the text to be encrypted
     * @param password password, encrypted password
     * @return returns the ciphertext, the content obtained after encryption. Encryption error returns null
     * /
    public static String encryptHex (String clearText, String password) {
        try {
            // 1 Get the encrypted ciphertext byte array
            byte [] cipherTextBytes = encrypt (clearText.getBytes (CHARACTER), pwdHandler (password));

            // 2 convert ciphertext byte array to HEX output ciphertext
            String cipherText = byte2hex (cipherTextBytes);

            // 3 returns HEX output ciphertext
            return cipherText;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        // encryption error returns null
        return null;
    }

    / **
     * HEX decryption
     * @param cipherText ciphertext with decrypted content
     * @param password password, decrypted password
     * @return returns the plaintext, decrypted content. Decryption error returns null
     * /
    public static String decryptHex (String cipherText, String password) {
        try {
            // 1 convert HEX output ciphertext to ciphertext byte array
            byte [] cipherTextBytes = hex2byte (cipherText);

            // 2 decrypt the ciphertext byte array to get the plaintext byte array
            byte [] clearTextBytes = decrypt (cipherTextBytes, pwdHandler (password));

            // 3 Transcode according to CHARACTER, return plain text string
            return new String (clearTextBytes, CHARACTER);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        } catch (Exception e) {
            e.printStackTrace ();
        }
        // decryption error returns null
        return null;
    }

    / * Byte array into hexadecimal string * /
    public static String byte2hex (byte [] bytes) {// a byte number,
        StringBuffer sb = new StringBuffer (bytes.length * 2);
        String tmp = "";
        for (int n = 0; n <bytes.length; n ++) {
            // convert integer to hexadecimal representation
            tmp = (java.lang.Integer.toHexString (bytes [n] & 0XFF));
            if (tmp.length () == 1) {
                sb.append ("0");
            }
            sb.append (tmp);
        }
        return sb.toString (). toUpperCase (); // convert to upper case
    }

    / * Convert hex string to byte array * /
    private static byte [] hex2byte (String str) {
        if (str == null || str.length () <2) {
            return new byte [0];
        }
        str = str.toLowerCase ();
        int l = str.length () / 2;
        byte [] result = new byte [l];
        for (int i = 0; i <l; ++ i) {
            String tmp = str.substring (2 * i, 2 * i + 2);
            result [i] = (byte) (Integer.parseInt (tmp, 16) & 0xFF);
        }
        return result;
    }

    public static void main (String [] args) {
        String test = encryptHex ("test", "1234567800000000");
        System.out.println (test);

        System.out.println (decryptHex (test, "1234567800000000"));
    }
}
Related Article

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.