一、加解密变量
public static String AES_SALT = "0123456789abcdef"; // 自定义该值
二、加密
/**
* 加密
*
* @param data 要加密的数据
* @param key 加盐,例:key = AES_SALT
* @return
* @throws Exception
*/
public static String enAes(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return new BASE64Encoder().encode(encryptedBytes);
}
三、解密
/**
* 解密
*
* @param data 要解密的数据
* @param key 加盐,例:key = AES_SALT
* @return
* @throws Exception
*/
public static String deAes(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] cipherTextBytes = new BASE64Decoder().decodeBuffer(data);
byte[] decValue = cipher.doFinal(cipherTextBytes);
return new String(decValue);
}