package org.tio.sitexxx.service.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-01-07 15:20
 *    desc   :
 * </pre>
 */
public class AESUtils {
    public static final String TOKEN = "dfkcmbhfgjlasfgf";
    // 使用给定的密钥创建 SecretKey
    public static SecretKey createKey() {
        return new SecretKeySpec(TOKEN.getBytes(), "AES");
    }

    // 加密方法
    public static String encrypt(String data) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, createKey());
            byte[] encryptedData = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedData); // 使用Base64编码以便于输出
        } catch (Exception e) {
            return "";
        }
    }

    // 解密方法
    public static String decrypt(String encryptedData) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, createKey());
            byte[] decodedData = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedData = cipher.doFinal(decodedData);
            return new String(decryptedData);
        } catch (Exception e){
            return "";
        }
    }
}
