package com.hx.util; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * AES加解密工具 * 使用该类,需要行替换local_policy.jar及us_export_policy.jar * @author ChenJiaHe * */ public class AesUtil { /**16位加密秘钥*/ public static final String SECRET = "huoXiong16816888"; /** * AES加密 * * @param str * 需要加密的明文 * @param secret * 秘钥 * @return 加密后的密文(base64编码字符串) */ public static String aesEncryp(String str, String secret) { if (null != str) { byte[] bytes = null; try { Base64 base64 = new Base64(); String ALGORITHM = "AES"; SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 生成密钥 Cipher c; c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, deskey); bytes = c.doFinal(str.getBytes("UTF-8")); if (bytes != null) { return new String(base64.encode(bytes)); } } catch (Exception e) { e.printStackTrace(); } } return null; } /** * AES解密 * * @param str * 需要解密的秘文 * @param secret * 秘钥 * @return 解密后的明文 */ public static String aesDecryp(String str, String secret) { try { Base64 base64 = new Base64(); String ALGORITHM = "AES"; SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 生成密钥 Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.DECRYPT_MODE, deskey); return new String(c.doFinal(base64.decode(str.getBytes("UTF-8"))), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; } /** * AES加密(固定秘钥) * * @param str 需要加密的明文 * @return 加密后的密文(base64编码字符串) */ public static String aesEncryp(String str) { String secret = SECRET; if (null != str) { byte[] bytes = null; try { Base64 base64 = new Base64(); String ALGORITHM = "AES"; SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 生成密钥 Cipher c; c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, deskey); bytes = c.doFinal(str.getBytes("UTF-8")); if (bytes != null) { return new String(base64.encode(bytes)); } } catch (Exception e) { e.printStackTrace(); } } return null; } /** * AES解密(固定秘钥) * * @param str 需要解密的秘文 * @return 解密后的明文 */ public static String aesDecryp(String str) { String secret = SECRET; try { Base64 base64 = new Base64(); String ALGORITHM = "AES"; SecretKey deskey = new SecretKeySpec(secret.getBytes("UTF-8"), ALGORITHM);// 生成密钥 Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.DECRYPT_MODE, deskey); return new String(c.doFinal(base64.decode(str.getBytes("UTF-8"))), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; } }