package com.playlet.common.utils;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @Date: 2024-03-30 13:15
 * @Author: 但星霖
 * @Version: v1.0
 * @Description:
 */
public class AesUtils {

    private static final Base64.Encoder encoder = Base64.getEncoder();
    private static final Base64.Decoder decoder = Base64.getDecoder();

    /**
     * ase 加密key
     */
    private static String aesKey = "ba826c895b099012133b2a889992f219";

    public static String aesEncrypt(String text) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] byteContent = text.getBytes(StandardCharsets.UTF_8);
            cipher.init(1, getSecretKey(aesKey));
            byte[] result = cipher.doFinal(byteContent);
            return encoder.encodeToString(result);
        } catch (Exception var5) {
            return null;
        }
    }

    public static String aesDecrypt( String text) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(2, getSecretKey(aesKey));
            byte[] result = cipher.doFinal(decoder.decode(text));
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception var4) {
            return  null;
        }
    }

    private static SecretKeySpec getSecretKey(String password) throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        kg.init(128, random);
        SecretKey secretKey = kg.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
    }

}
