package com.bonus.common.core.utils.encryption;

import com.bonus.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

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

/**
 *
 * AES加密工具类
 * @author HeiZi
 */
@Slf4j
public class AesCbcUtils {
    //使用AES-256-CBC加密模式，key需要为16位,key和iv可以相同！
    /**
     * 密钥算法
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * 加密/解密算法 / 工作模式 / 填充方式
     * Java 6支持PKCS5Padding填充方式
     * Bouncy Castle支持PKCS7Padding填充方式
     */
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

    /**
     * 偏移量，只有CBC模式才需要
     */
    private final static String IV_PARAMETER = "1234567812345678";


    /**
     * AES要求密钥长度为128位或192位或256位，java默认限制AES密钥长度最多128位
     */
    public static String sKey = "zhgd@bonus@zhgd@bonus@1234567890";

    /**
     * 编码格式导出
     */
    public static final String ENCODING = "utf-8";

    static {
        //如果是PKCS7Padding填充方式，则必须加上下面这行
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES加密
     *（CBC模式）
     * @param source 源字符串
     * @param
     * @throws Exception
     * @return 加密后的密文
     */
    public static String encrypt(String source )   {
        try{
            String key=sKey;
            byte[] sourceBytes = source.getBytes(ENCODING);
            byte[] keyBytes = key.getBytes(ENCODING);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(ENCODING));
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM), iv);
            byte[] decrypted = cipher.doFinal(sourceBytes);
            return Base64.encodeBase64String(decrypted);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return null;
    }

    public static void main(String[] args) {
    //    String  json="";

        String param="curryDay=2024-08-07";
        String data2=encrypt(param);
        System.err.println(data2);

        String  json="{\"username\":\"guest\",\"password\":\"admin@123\"}";
        String data=encrypt(json);
        System.err.println(data);
        String jm=decrypt("HpouTnMjl/Of1leko+SHm3D436XwOROzSOhMqU0ZNUISeD/iXPK9t49sMEuBw3YO");
        String jiemi=decrypt(data);
        System.err.println(jm);
        System.err.println(jiemi);
    }

    /**
     * AES解密
     *（CBC模式）
     * @param data 加密后的密文
     * @param
     * @throws Exception
     * @return 源字符串
     */
    public static String decrypt(String data)  {
        try{
            String  encryptStr="";
            if(StringUtils.isNotEmpty(data)){
                encryptStr=data.replace(" ","+");
            }
            String key=sKey;
            byte[] sourceBytes = Base64.decodeBase64(encryptStr);
            byte[] keyBytes = key.getBytes(ENCODING);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(ENCODING));
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM), iv);
            byte[] decoded = cipher.doFinal(sourceBytes);
            return new String(decoded, ENCODING);
        }catch (Exception e){
            log.info("------------------->请求加密参数不正确");
            log.error(e.toString(),e);
        }
        return null;
    }

}
