package com.dsideal.FengHuang.Util; import com.jfinal.kit.PropKit; import com.jfinal.log.Log; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; @SuppressWarnings("unchecked") public class MysqlAesUtil { //在独立的main函数中,使用下面的方式进行声明logback对象 private static Log log = Log.getLog(MysqlAesUtil.class); /** * 功能:调用默认的密码进行加密 * 作者:黄海 * 时间:2019-01-07 * @param sSrc * @return * @throws Exception */ public static String Encrypt(String sSrc) throws Exception { String cKey=PropKit.get("AesPwd"); return Encrypt(sSrc,cKey); } /** * 功能:调用默认的密码进行解密 * 作者:黄海 * 时间:2019-01-07 * @param sSrc * @return */ public static String Decrypt(String sSrc) { String cKey=PropKit.get("AesPwd"); return Decrypt(sSrc,cKey); } // 加密 private static String Encrypt(String sSrc, String sKey) throws Exception { if (sKey == null) { log.info("Key为空null"); return null; } // 判断Key是否为16位 if (sKey.length() != 16) { log.info("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式" cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。 } // 解密 private static String Decrypt(String sSrc, String sKey) { try { // 判断Key是否正确 if (sKey == null) { log.info("Key为空null"); return null; } // 判断Key是否为16位 if (sKey.length() != 16) { log.info("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密 try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original,"utf-8"); return originalString; } catch (Exception e) { log.error(e.toString()); return sSrc; } } catch (Exception ex) { log.error(ex.toString()); return sSrc; } } }