package com.ruoyi.business.utils;


import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    // 密钥  必须是16位, 自定义,
    // 如果不是16位, 则会出现InvalidKeyException: Illegal key size
    //  解决方案有两种：
    //1.需要安装Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files(可以在Oracle下载).
    //2.设置设置key的长度为16个字母和数字的字符窜（128 Bit/8=16字符）就不报错了。
    // 偏移量
    private static int offset = 16;
    private static String transformation = "AES/CBC/PKCS5Padding";
    private static String algorithm = "AES";

    /**
     * 加密
     *
     * @param content 内容
     * @return 加密内容
     */
    public static String encrypt(String content) {
        String key = ObjectUtil.cloneIfPossible("TARGET20241111_?");
        return encrypt(content, ObjectUtil.cloneIfPossible(key));
    }

    /**
     * 解密
     *
     * @param content 内容
     * @return 解密内容
     */
    public static String decrypt(String content) {
        String key = ObjectUtil.cloneIfPossible("TARGET20241111_?");
        return decrypt(content, ObjectUtil.cloneIfPossible(key));
    }

    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @param key     加密密码
     * @return 加密内容
     */
    private static String encrypt(String content, String key) {
        try {
            SecretKeySpec skey = new SecretKeySpec(ObjectUtil.cloneIfPossible(key.getBytes()), algorithm);
            IvParameterSpec iv = new IvParameterSpec(ObjectUtil.cloneIfPossible(key.getBytes()), 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            String charset = "utf-8";
            byte[] byteContent = content.getBytes(charset);
            cipher.init(Cipher.ENCRYPT_MODE, skey, iv);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return new Base64().encodeToString(result); // 加密
        } catch (Exception e) {
            // LogUtil.exception(e);
        }
        return null;
    }

    /**
     * AES（256）解密
     *
     * @param content 待解密内容
     * @param key     解密密钥
     * @return 解密之后
     */
    private static String decrypt(String content, String key) {
        try {

            SecretKeySpec skey = new SecretKeySpec(ObjectUtil.cloneIfPossible(key.getBytes()), algorithm);
            IvParameterSpec iv = new IvParameterSpec(ObjectUtil.cloneIfPossible(key.getBytes()), 0, offset);
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化
            byte[] result = cipher.doFinal(new Base64().decode(content));
            return new String(result); // 解密
        } catch (Exception e) {
            //LogUtil.exception(e);
        }
        return null;
    }

}
