package com.nq.utils; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * @program: dabaogp * @description: * @create: 2026-03-02 15:11 **/ public class AesEncryptUtil { public static String encrypt(String data, String key, String iv) throws Exception { // 直接使用字符串的 UTF-8 字节作为密钥和 IV(需确保长度为16) byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); byte[] ivBytes = iv.getBytes(StandardCharsets.UTF_8); // 验证长度(可选) if (keyBytes.length != 16 || ivBytes.length != 16) { throw new IllegalArgumentException("Key and IV must be 16 bytes long (16 ASCII characters)"); } SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encrypted); } }