package com.onekeycall.videotablet.utils; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { // 使用ECB模式(无需IV) private static final String ALGORITHM = "AES/ECB/PKCS5Padding"; // 密钥长度要求:128/192/256位(16/24/32字节) private static final int KEY_LENGTH = 32; // 256位密钥 // 从环境变量获取密钥(生产环境推荐) // private static final String SECRET_KEY = System.getenv("AES_KEY"); // 测试用密钥(确保长度符合要求) private static final String SECRET_KEY = "dasdasdasdawqeq12345312gs6h092fs"; /** * 加密方法(ECB模式) * @param plaintext 明文 * @return Base64编码的密文 */ public static String encrypt(String plaintext) { try { // 验证密钥长度 validateKey(); // 初始化加密器 Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); // 加密数据 byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encrypted); } catch (Exception e) { throw new RuntimeException("加密失败", e); } } /** * 解密方法(ECB模式) * @param ciphertext Base64编码的密文 * @return 解密后的明文 */ public static String decrypt(String ciphertext) { try { // 验证密钥长度 validateKey(); // 初始化解密器 Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec); // 解密数据 byte[] decodedBytes = Base64.getDecoder().decode(ciphertext); byte[] decrypted = cipher.doFinal(decodedBytes); return new String(decrypted, StandardCharsets.UTF_8); } catch (Exception e) { throw new RuntimeException("解密失败", e); } } /** * 验证密钥长度是否符合要求 */ private static void validateKey() { byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8); if (keyBytes.length != 16 && keyBytes.length != 24 && keyBytes.length != 32) { throw new IllegalArgumentException("无效的密钥长度。AES要求密钥长度为16(128位)、24(192位)或32字节(256位)。" + "当前长度: " + keyBytes.length + "字节"); } } }