基于javax.crypto包的AES加解密工具类:
AES加密
/**
* @param cleartext 待加密明文
* @param keyLength 密钥长度:128、192、256(密钥长度与安全性成正比,与性能成反比)
* @param workingPattern 工作模式
* @param fillStyle 填充模式
* @return java.lang.String 返回加密后的字符串
* @Description
**/
public static String enAES(String cleartext,String key, int keyLength, String workingPattern, String fillStyle) throws Exception {
//自定义加密规则
String cipherInitInfo = "AES/" + workingPattern + "/" + fillStyle;
//构造加密器
Cipher cipher = Cipher.getInstance(cipherInitInfo);
//获取明文字节数组
byte[] byteContent = cleartext.getBytes("utf-8");
//使用加密模式,传入密钥
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key,keyLength));
//加密操作
byte[] result = cipher.doFinal(byteContent);
//加密后使用BASE64编码转换
return new BASE64Encoder().encode(result);
}
其中getSecretKey(key,keyLength)
方法是获取密钥,源码后面附上。
AES解密
public static String deAES(String ciphertext ,String key,int keyLength, String workingPattern, String fillStyle) throws Exception{
String cipherInitInfo = "AES/" + workingPattern + "/" + fillStyle;
Cipher cipher = Cipher.getInstance(cipherInitInfo);
//用BASE64解码
byte[] byteContent = new BASE64Decoder().decodeBuffer(ciphertext);
//使用解密模式,传入密钥
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key,keyLength));
return new String(cipher.doFinal(byteContent));
}
获取密钥方法
/**
* @param key 自定义密钥种子
* @param keyLength 密钥长度
* @return javax.crypto.spec.SecretKeySpec
* @Description
**/
private static SecretKeySpec getSecretKey(String key,int keyLength) throws NoSuchAlgorithmException {
//密钥生产者
KeyGenerator kgen = KeyGenerator.getInstance("AES");
//初始化密钥生产信息。SecureRandom这里指定种子key.getBytes(),意味着每次所获取的随机数一样
kgen.init(keyLength, new SecureRandom(key.getBytes()));
//获取密钥
SecretKey secretKey = kgen.generateKey();
//返回AES专用密钥
return new SecretKeySpec(secretKey.getEncoded(),"AES");
}
参考文章:
http://www.sohu.com/a/198681357_505794
https://www.cnblogs.com/yshyee/p/7050330.html