public class AesEncrypt {
// 密钥
public static String AESKey = "1234567890abcdef1234567890abcdef";
public static String AESIV = "1234567890abcdef";
private static String charset = "utf-8";
// 偏移量 16对应128位
private static int offset = 16;
private static String transformation = "AES/CBC/PKCS5Padding";
private static String algorithm = "AES";
//加密
public static String encrypt(String content) {
try {
SecretKeySpec skey = new SecretKeySpec(AESKey.getBytes(), algorithm);
IvParameterSpec iv = new IvParameterSpec(AESIV.getBytes(), 0, offset);
Cipher cipher = Cipher.getInstance(transformation);
byte[] byteContent = content.getBytes(charset);
cipher.init(Cipher.ENCRYPT_MODE, skey, iv);// 初始化
byte[] result = cipher.doFinal(byteContent);
return new Base64().encodeToString(result); // 加密
} catch (Exception e) {
throw new DaException(DaException.SYSTEM_ERROR,e.getMessage());
}
}
//解密
public static String decrypt(String content) {
try {
SecretKeySpec skey = new SecretKeySpec(AESKey.getBytes(), algorithm);
IvParameterSpec iv = new IvParameterSpec(AESIV.getBytes(), 0, offset);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化
byte[] result = cipher.doFinal(new Base64().decode(content));
return new String(result); // 解密
} catch (Exception e) {
throw new DaException(DaException.SYSTEM_ERROR,e.getMessage());
}
}
}
密钥要是大于128的话会报 java.security.InvalidKeyException: Illegal key size 异常
因为密钥长度是受限制的, java运行时环境读到的是受限的policy文件. 文件位于${java_home}/jre/lib/security, 这种限制是因为美国对软件出口的控制.
处理办法: 在官方网站下载JCE无限制权限策略文件
jdk 5: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-plat-419418.html#jce_policy-1.5.0-oth-JPR
jdk6: http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html
JDK7的下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JDK8的下载地址: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt
如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件
如果安装了JDK,还要将两个jar文件也放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件