package com.chinaztt.mes.basic.util; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * Author: Realchen * Date: 2020/7/23 16:23 * Description: AES工具类 * * @author ZTT */ public class AesUtils { /** * 密匙 */ private static final String KEY = ")O[NB]6,YF}+efcaj{+oESb9d8>Z'e9M"; /** * 偏移量 */ private static final String OFFSET = "L+\\~f4,Ir)b$=pkf"; /** * 编码 */ private static final String ENCODING = "UTF-8"; /** * 算法 */ private static final String ALGORITHM = "AES"; /** * 默认的加密算法 */ private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; /** * 加密 * * @param data * @return String * @throws Exception * @author tyg * @date 2018年6月28日下午2:50:35 */ public static String encrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM); //使用CBC模式,需要一个向量iv,可增加加密算法的强度 IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING)); //此处使用BASE64做转码。 return new BASE64Encoder().encode(encrypted); } /** * 解密 * * @param data * @return String * @throws Exception * @author tyg * @date 2018年6月28日下午2:50:43 */ public static String decrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM); //使用CBC模式,需要一个向量iv,可增加加密算法的强度 IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] buffer = new BASE64Decoder().decodeBuffer(data); byte[] encrypted = cipher.doFinal(buffer); //此处使用BASE64做转码。 return new String(encrypted, ENCODING); } }