package org.wfc.common.core.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

public class AESUtil {
    // AES密钥算法
    private static final String KEY_ALGORITHM = "AES";
    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    private static final String KEY = "EolSdjfd89v2PubN";

    //CBC加密偏移量
    private static final String IVCODE = "EjlnujOBvlv2PubN";

    /**
     * AES加密
     */
    public static String encrypt(String data) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            IvParameterSpec iv = new IvParameterSpec(IVCODE.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * AES解密
     */
    public static String decrypt(String encryptedData) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), KEY_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IVCODE.getBytes());
            Security.addProvider(new BouncyCastleProvider());
            byte[] encryptedBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(encryptedData);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 验证
//    public static void main(String[] args) throws Exception {
//        String data = "AfPgwFAmo9K7KCqiiGpNRCyQMSxI6V33eH-nEMnVndJNVEYOEOEn5wSPkHUybfzcjDLnBejt-RKnIfqX";
//        String encryptedData = encrypt(data); // 加密数据
//        String decryptedData = decrypt(encryptedData); // 解密数据
//        System.out.println("加密后的数据: " + encryptedData);
//        System.out.println("解密后的数据: " + decryptedData);
//    }
}