package com.platform.utils;

import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

/**
 * @author abnerhou
 * @date 2020/5/5 10:36
 * @desciption
 */
@Slf4j
public class AES {

    public static boolean initialized = false;

    /**
     * AES解密
     *
     * @param content
     *            密文
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            log.info("============开始解密==============");
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));
            byte[] result = cipher.doFinal(content);
            log.info("============解密结束==============");
            return result;
        } catch (NoSuchAlgorithmException e) {
            log.info("解密出异常：{}" , e);
        } catch (NoSuchPaddingException e) {
            log.info("解密出异常：{}" , e);
        } catch (InvalidKeyException e) {
            log.info("解密出异常：{}" , e);
        } catch (IllegalBlockSizeException e) {
            log.info("解密出异常：{}" , e);
        } catch (BadPaddingException e) {
            log.info("解密出异常：{}" , e);
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            log.info("解密出异常：{}" , e);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.info("解密出异常：{}" , e);
        }
        return null;
    }

    public static void initialize() {
        if (initialized)
            return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    // 生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }
}
