package com.sckw.core.utils;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @desc:
 * @author: Lt
 * @date: 2024-05-22
 */
public class AESUtil {
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final int KEY_SIZE = 128;

    /**
    * @Description:
    * @Author: Lt
    * @Date: 2024/5/22 15:13
    */
    public static String encrypt(String data, String salt) throws Exception
    {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(salt.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }


    /**
    * @Description: AES解码
    * @Author: Lt
    * @Date: 2024/5/22 15:14
    */
    public static String decrypt(String encryptedData, String salt) throws Exception
    {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(salt.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

    /**
     * 生成一个指定长度的随机盐值。
     *
     * @param length 盐值的长度。
     * @return 生成的盐值。
     */
    public static String generateSalt(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be a positive number");
        }

        // 创建一个SecureRandom对象
        SecureRandom random = new SecureRandom();
        // 生成一个随机的字节数组
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);

        // 将字节数组编码为Base64字符串，以缩短长度并保证字符串只包含可打印字符
        return Base64.getEncoder().encodeToString(bytes);
    }

}

