package com.ruoyi.web.modules.openstats.support;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.openstats.constant.OpenStatsConstants;

/**
 * Open API Token：AES-128-CBC 解密后校验 UUID 格式
 */
@Component
public class OpenStatsTokenCryptoSupport
{
    public boolean validateEncryptedToken(String encryptedToken)
    {
        String plain = decrypt(encryptedToken);
        return isUuid(plain);
    }

    public String decrypt(String encryptedToken)
    {
        if (StringUtils.isEmpty(encryptedToken))
        {
            return null;
        }
        try
        {
            byte[] cipherBytes = Base64.getDecoder().decode(encryptedToken.trim());
            Cipher cipher = Cipher.getInstance(OpenStatsConstants.AES_TRANSFORMATION);
            SecretKeySpec keySpec = new SecretKeySpec(
                    OpenStatsConstants.AES_KEY.getBytes(StandardCharsets.UTF_8), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(
                    OpenStatsConstants.AES_IV.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] plainBytes = cipher.doFinal(cipherBytes);
            return new String(plainBytes, StandardCharsets.UTF_8).trim();
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    public boolean isUuid(String value)
    {
        if (StringUtils.isEmpty(value))
        {
            return false;
        }
        try
        {
            UUID.fromString(value.trim());
            return true;
        }
        catch (IllegalArgumentException ex)
        {
            return false;
        }
    }
}
