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

// package com.cdp.product.security.encode;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Base64.Encoder;

public class EncryptionUtils
{
    public EncryptionUtils()
    {}

    private static byte[] aesEncryptToBytes( String content, String encryptKey ) throws Exception
    {
        Cipher cipher = Cipher.getInstance( "AES/CBC/NoPadding" );
        byte[] dataBytes = content.getBytes( "utf-8" );
        int blockSize = cipher.getBlockSize();
        int plaintextLength = dataBytes.length;

        if ( plaintextLength % blockSize != 0 )
        {
            plaintextLength += blockSize - plaintextLength % blockSize;
        }

        byte[] plaintext = new byte[plaintextLength];

        SecretKeySpec keySpec = new SecretKeySpec( encryptKey.getBytes(), "AES" );
        IvParameterSpec ivSpec = new IvParameterSpec( encryptKey.getBytes() );

        System.arraycopy( dataBytes, 0, plaintext, 0, dataBytes.length );

        cipher.init( 1, keySpec, ivSpec );

        return cipher.doFinal( plaintext );
    }

    public static String aesEncrypt( String content, String encryptKey )
            throws Exception
    {
        try
        {
            Encoder encoder = Base64.getEncoder();
            String encode = encoder.encodeToString(aesEncryptToBytes( content, encryptKey ));

            return encode;
        }
        catch ( Exception var3 )
        {
            throw new Exception( "加密失败！" );
        }
    }
}
