java AES encryption and decryption

Keywords: Programming Apache Java

AES encryption and decryption tool class

package com.yan.demo;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

/**
 * @ClassName AES
 * @Description TODO
 * @Author lyq
 * @Date 2020/2/12 9:33 Afternoon
 * @Version 1.0
 */
public class AES {
    public static final String ENCRYPT_MODE_CBC = "CBC";
    public static final String ENCRYPT_MODE_ECB = "ECB";
    /**
     * Default encryption type
     */
    private static final String _ENCRYPT_MODE = "CBC";


    /**
     * AES encryption
     *
     * @param plaintext Plaintext
     * @param key secret key
     * @return AES ciphertext value of the string
     */
    public static String encrypt(String plaintext, String key) {
        return encrypt(plaintext,key,_ENCRYPT_MODE);
    }

    /**
     * AES Decrypt
     *
     * @param cipertext ciphertext
     * @param key secret key
     * @return The plaintext of the ciphertext
     */
    public static String decrypt(String  cipertext, String key) {
        return decrypt(cipertext,key,_ENCRYPT_MODE);
    }



    /**
     * AES encryption
     *
     * @param plainText Plaintext
     * @param key secret key
     * @param encryptMode AES Encryption mode, CBC or ECB
     * @return AES ciphertext value of the string
     */
    public static String encrypt(String plainText, String key,String encryptMode) {
        if (StringUtils.isEmpty(key)|| StringUtils.isEmpty(plainText)) {
            return null;
        }

        try {
            key = getMD5(key);
            byte[] raw = key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/"+encryptMode+"/PKCS5Padding");
            if(encryptMode==AES.ENCRYPT_MODE_ECB) {
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            }else {
                IvParameterSpec iv = new IvParameterSpec(key.getBytes("utf-8"));//Using CBC mode, we need a vector iv to increase the strength of encryption algorithm
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            }
            byte[] encrypted = cipher.doFinal(plainText.getBytes("utf-8"));
            String encryptedStr=new String(new BASE64Encoder().encode(encrypted));
            //Here, BASE64 is used for transcoding function, and it can play the role of twice encryption.
            return encryptedStr;
            //return new String(encrypted);
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * AES Decrypt
     *
     * @param cipherText ciphertext
     * @param key secret key
     * @param encryptMode AES Encryption mode, CBC or ECB
     * @return The plaintext of the ciphertext
     */
    public static String decrypt(String cipherText, String key,String encryptMode) {
        if (StringUtils.isEmpty(key)|| StringUtils.isEmpty(cipherText)) {
            return null;
        }
        try {
            key=getMD5(key);
            byte[] raw = key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher=Cipher.getInstance("AES/"+encryptMode+"/PKCS5Padding");
            if(encryptMode==AES.ENCRYPT_MODE_ECB) {
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            }else {
                //Using CBC mode, we need a vector iv to increase the strength of encryption algorithm
                IvParameterSpec iv = new IvParameterSpec(key.getBytes("utf-8"));
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            }
            //Decrypt with base64 first
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(cipherText);
            //byte[] encrypted1 = CipherText.getBytes();
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
    /**
     * MD5 encryption
     *
     * @param s String to MD5 conversion
     * @return 8-24 bits of MD5 value of the string
     */
    public static String getMD5(String s){
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

        try {
            byte[] btInput = s.getBytes();
            // Get the MessageDigest object of MD5 digest algorithm
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // Update summary with specified bytes
            mdInst.update(btInput);
            // Get ciphertext
            byte[] md = mdInst.digest();
            // Convert ciphertext to hexadecimal string form
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str).substring(8,24);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}



Brief description of AES encryption algorithm

AES encryption

  1. Verify that the parameter is empty.
  2. MD5 encrypt the secret key (the length after encryption is 16).
  3. AES encryption of plaintext.
  4. After AES encryption, the ciphertext is encrypted with base64, and the transcoding result is returned.

AES decryption

  1. Verify that the parameter is empty.
  2. MD5 encrypt the secret key (the length after encryption is 16).
  3. Decrypt the ciphertext with base64.
  4. The data decrypted by base64 will be used for AES decryption, and the decrypted content will be returned.

****Code is not easy. If it helps you, please pay attention****

****Love technology love life QQ group: 894109590****

Posted by kam_uoc on Fri, 14 Feb 2020 08:17:13 -0800