需提前引入依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.15</version>
</dependency>
import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.symmetric.AES;
import java.nio.charset.StandardCharsets;
/**
* @author rikka
* AES加密、解密工具(以当前时间戳作盐)
* */
public class AesUtil {
/**
* 加密,适用于IOS等移动端(PKCS7Padding)
* @param key 加密密钥,AES明文规定密钥长度必须16字节
* @param content 加密内容
* */
public static String doEncrypt(String key, String content) {
//文本直接加密仍有风险,这里以当前时间戳作前缀手动加盐
content = System.currentTimeMillis() + content;
AES aes = new AES("ECB", "PKCS7Padding",
key.getBytes(StandardCharsets.UTF_8));
try {
// 加密为16进制表示
return aes.encryptBase64(content.getBytes(StandardCharsets.UTF_8));
}catch (CryptoException e) {
e.printStackTrace();
throw new RuntimeException("密钥必须是16字节!");
}
}
/**
* 解密
* @param key 加密密钥
* @param content 需解密内容
* */
public static String doDecrypt(String key, String content) {
AES aes = new AES("ECB", "PKCS7Padding",
key.getBytes(StandardCharsets.UTF_8));
try {
//时间戳为13位数字,13位后的为加密内容
return aes.decryptStr(content).substring(13);
} catch (CryptoException e) {
e.printStackTrace();
throw new RuntimeException("密钥必须是16字节!");
}
}
}