public class AESUtil {
public static final String algorithm = "AES";
// AES/CBC/NOPaddin
// AES 默认模式
// 使用CBC模式, 在初始化Cipher对象时, 需要增加参数, 初始化向量IV : IvParameterSpec iv = new
// IvParameterSpec(key.getBytes());
// NOPadding: 使用NOPadding模式时, 原文长度必须是8byte的整数倍
// PKCS5Padding: 自动填充
public static final String transformation = "AES/CBC/PKCS5Padding";
public static final String key = "1234567812345678";
/***
* 加密
* @param original 需要加密的参数(注意必须是16位)
* @return
* @throws Exception
*/
public static String encryptByAES(String original) throws Exception {
// 获取Cipher
Cipher cipher = Cipher.getInstance(transformation);
// 生成密钥
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
// 指定模式(加密)和密钥
// 创建初始化向量
IvParameterSpec iv = new IvParameterSpec(key.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// cipher.init(Cipher.ENCRYPT_MODE, keySpec);
// 加密
byte[] bytes = cipher.doFinal(original.getBytes());
return encryptBASE64(bytes);
}
/**
* 解密
* @param encrypted 需要解密的参数
* @return
* @throws Exception
*/
public static String decryptByAES(String encrypted) throws Exception {
// 获取Cipher
Cipher cipher = Cipher.getInstance(transformation);
// 生成密钥
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm);
// 指定模式(解密)和密钥
// 创建初始化向量
IvParameterSpec iv = new IvParameterSpec(key.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
// cipher.init(Cipher.DECRYPT_MODE, keySpec);
// 解密
byte[] bytes = cipher.doFinal(decryBASE64(encrypted));
return new String(bytes);
}
/***
* BASE64解密
* @param key
* @return
* @throws Exception
*/
public static byte[] decryBASE64(String key) throws Exception{
return (new BASE64Decoder()).decodeBuffer(key);
}
/***
* BASE64加密
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception{
return (new BASE64Encoder()).encode(key);
}
}
标签:AES,加密,String,Exception,return,Cipher,key,Java,throws
From: https://www.cnblogs.com/eaglex3/p/18098204