/*
 * @Author: Kane
 * @Date: 2023-05-25 11:14:03
 * @LastEditors: Kane
 * @FilePath: /NewCitizenQueryResult/src/main/java/com/cpic/xim/utils/decryption/DecryptionUtils.java
 * @Description: 
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */
package com.cpic.xim.utils.security.decode;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import java.util.Base64;
import java.util.Base64.Decoder;

public class DecryptionUtils
{
    public DecryptionUtils()
    {}

    private static String aesDecryptByBytes( byte[] encryptBytes, String decryptKey )
            throws Exception
    {
        Cipher cipher = Cipher.getInstance( "AES/CBC/NoPadding" );
        SecretKeySpec keySpec = new SecretKeySpec( decryptKey.getBytes(), "AES" );
        IvParameterSpec ivSpec = new IvParameterSpec( decryptKey.getBytes() );

        cipher.init( 2, keySpec, ivSpec );

        byte[] decryptBytes = cipher.doFinal( encryptBytes );

        String result = new String( decryptBytes );

        if ( StringUtils.isNotBlank( result ) )
        {
            result = result.trim();
        }

        return result;
    }

    public static String aesDecrypt( String encryptStr, String decryptKey ) throws Exception
    {
        try
        {
            return StringUtils.isBlank( encryptStr ) ? null
                    : aesDecryptByBytes( base64Decode( encryptStr ), decryptKey );
        }
        catch ( Exception var3 )
        {
            throw new Exception( "解密失败！" );
        }
    }

    private static byte[] base64Decode( String base64Code ) throws Exception
    {
        Decoder decoder = Base64.getDecoder();
        byte[] buffer = decoder.decode( base64Code );

        return StringUtils.isBlank( base64Code ) ? null : buffer;
    }
}
