1
zj
2026-03-23 efb07bcec37c49228d9760794f215c8549243ad2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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);
    }
 
}