package com.taoke.autopay.utils.encrypt;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.KeyGenerator;
|
import javax.crypto.SecretKey;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.security.SecureRandom;
|
import java.util.Base64;
|
|
/**
|
* AES加密解密工具类
|
*/
|
public class AESUtil {
|
|
private static final String ALGORITHM = "AES";
|
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
|
|
/**
|
* AES加密
|
* @param content 待加密内容
|
* @param key 加密密钥
|
* @return 加密后的字符串
|
*/
|
public static String encrypt(String content, String key) {
|
try {
|
// 创建AES密钥
|
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
|
|
// 创建密码器
|
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
|
|
// 初始化为加密模式
|
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
|
|
// 执行加密操作
|
byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
|
|
// 使用Base64编码返回
|
return Base64.getEncoder().encodeToString(encrypted);
|
} catch (Exception e) {
|
throw new RuntimeException("AES加密失败", e);
|
}
|
}
|
|
/**
|
* AES解密
|
* @param content 待解密内容
|
* @param key 解密密钥
|
* @return 解密后的字符串
|
*/
|
public static String decrypt(String content, String key) {
|
try {
|
// 使用Base64解码
|
byte[] encrypted = Base64.getDecoder().decode(content);
|
|
// 创建AES密钥
|
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
|
|
// 创建密码器
|
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
|
|
// 初始化为解密模式
|
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
|
|
// 执行解密操作
|
byte[] decrypted = cipher.doFinal(encrypted);
|
|
// 转换为字符串返回
|
return new String(decrypted, "utf-8");
|
} catch (Exception e) {
|
throw new RuntimeException("AES解密失败", e);
|
}
|
}
|
|
/**
|
* 生成AES密钥
|
* @return 生成的密钥字符串
|
*/
|
public static String generateKey() {
|
try {
|
// 创建KeyGenerator对象
|
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
|
|
// 初始化密钥长度为128位
|
keyGenerator.init(128);
|
|
// 生成密钥
|
SecretKey secretKey = keyGenerator.generateKey();
|
|
// 获取密钥字节数组
|
byte[] keyBytes = secretKey.getEncoded();
|
|
// 使用Base64编码返回
|
return Base64.getEncoder().encodeToString(keyBytes);
|
} catch (Exception e) {
|
throw new RuntimeException("生成AES密钥失败", e);
|
}
|
}
|
|
/**
|
* 根据密码生成固定密钥
|
* @param password 密码
|
* @return 固定密钥
|
*/
|
public static String generateKeyByPassword(String password) {
|
try {
|
// 创建随机数生成器
|
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
|
secureRandom.setSeed(password.getBytes());
|
|
// 创建KeyGenerator对象
|
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
|
|
// 初始化随机数生成器
|
keyGenerator.init(128, secureRandom);
|
|
// 生成密钥
|
SecretKey secretKey = keyGenerator.generateKey();
|
|
// 获取密钥字节数组
|
byte[] keyBytes = secretKey.getEncoded();
|
|
// 使用Base64编码返回
|
return Base64.getEncoder().encodeToString(keyBytes);
|
} catch (Exception e) {
|
throw new RuntimeException("根据密码生成密钥失败", e);
|
}
|
}
|
}
|