package com.sqx.modules.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {

    // 密钥（必须是16/24/32字节的长度）
    private static final String KEY = "1234567890abcdef"; // 16字节 = 128位

    // 算法/模式/填充
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     */
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * 解密
     */
    public static String decrypt(String base64Encrypted) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decodedBytes = Base64.getDecoder().decode(base64Encrypted);
        byte[] decrypted = cipher.doFinal(decodedBytes);
        return new String(decrypted, "UTF-8");
    }

    // 测试
    public static void main(String[] args) throws Exception {
        String plainText = "210421200001084233";
        String encrypted = encrypt(plainText);
        String decrypted = decrypt(encrypted);

        System.out.println("原文: " + plainText);
        System.out.println("加密后: " + encrypted);
        System.out.println("解密后: " + decrypted);
    }
}

