package com.seeyon.apps.src_flowIntegration.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesUtil {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String CHARSET = "UTF-8";

    public static String encrypt(String content, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(CHARSET));
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encrypted = cipher.doFinal(content.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String encrypted, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(CHARSET));
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decoded = Base64.getDecoder().decode(encrypted);
        return new String(cipher.doFinal(decoded), CHARSET);
    }


    public static void main(String[] args) {
        // 测试用例（注意：AES-128的key和iv长度必须为16字节，AES-256为32字节）
        String testContent = "这是一段需要加密的测试数据，包含中文和英文：Hello AES!";
        // 16字节的密钥（AES-128）
        String testKey = "1234567890abcdef";
        // 16字节的IV向量
        String testIv = "abcdef1234567890";

        try {
            System.out.println("原始内容：" + testContent);

            // 加密
            String encrypted = AesUtil.encrypt(testContent, testKey, testIv);
            System.out.println("加密后：" + encrypted);

            // 解密
            String decrypted = AesUtil.decrypt(encrypted, testKey, testIv);
            System.out.println("解密后：" + decrypted);

            // 验证加密解密一致性
            if (testContent.equals(decrypted)) {
                System.out.println("\n✅ 测试通过：加密解密结果一致，数据未被篡改！");
            } else {
                System.out.println("\n❌ 测试失败：加密解密结果不一致！");
            }
        } catch (Exception e) {
            System.err.println("\n❌ 测试过程中发生异常：");
            e.printStackTrace();
        }
    }


}
