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@Bonu$123456";

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

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

    /**
     * AES加密
     * （CBC模式）
     *
     * @param source 源字符串
     * @param
     * @return 加密后的密文
     * @throws Exception
     */
    public static String encrypt(String source, String key, String encoding, String ivParameter, String cipherAlgorithm, String keyAlgorithm) {
        try {
            byte[] sourceBytes = source.getBytes(encoding);
            byte[] keyBytes = key.getBytes(encoding);
            Cipher cipher = Cipher.getInstance(cipherAlgorithm, "BC");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes(encoding));
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, keyAlgorithm), 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  json="{\"username\":\"guest\",\"password\":\"admin@123\"}";
//        String data=encrypt(json);
//        System.err.println(data);
//        String jm=decrypt("\"yeCxaGhmdDt+zDsKPr1prukR15BfIMLMOYIFKdgffGpMV76qVD8ANU4zsLiRZ87+7hd1Yje182nHhUOp/TeYCRuuUPQzmuXH7ikYVEWR1Rmc8uLq3G/BTMU6wFMSRFDBXARRl+dvnpyfX+MleF0KB1OAeuOIKv1gQPskmvDiFAniUlowf/96ZzMl7Bokqc/Lse8lMV92IQB14yQNa0+u/2kvdirzrcq+HCt9K8Ot3C59mjDqg49WoM65LEmaHmZqzdmmjbQlGH7ZOAFTLvF5kPzUsMz5Uim1uNvByB3eLFohc1UgB28DWoTyh43sRMPpq3S1BB20gcrBf3uVra/4qehBr3z98CGhGRyKHbjsCKl0Ri6YO1rp5aMRd9Y3wbOJFrZXFag5iifQx+ooDBeu6h1KCb5JfCjyAmw9+pgEL6X3eELPzK13XjblDyEikjx2Edv45MGsC0DUcjvz/Sb4E/8rn3o1Ep7W31xNCdn5mzZ8VO9POhE3DMK6woeN2C7TW+7YO/Zs9e4zKLS4vThvk5urCn2Ff2HkVBzoPtP2imuqQrY8898sbLllyaJEG0DPSrCf985ZgVa03JsO/EkMr3KAiHV5SHBZS1XEXqjdpL+YEdOnlfBXUk83kJhLj9rhUrTFza7ednQSzjq4XpIJJVy2aJhhj1chsmIM1Xl//0Dbak9Lb6VUq5Xr2IFAjNTgyxwtcFCdEvp4YZCSP6kqWgEpeAVlejyYOcNckUnWkjeHjtfgwvVsvUjWzyIRFCa7m/oY28xBV16RmW/r4XXquqKVdbPtATzrmf7pJCynXZ3IPd9ZGc1OTLnss9Ln9XNTH0E/I4Ma95fn9uxA+sOQkQ==\"");
//        String jiemi=decrypt(data);
//        System.err.println(jm);
//        System.err.println(jiemi);
//    }

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

}
