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

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.UUID;
import javax.crypto.Cipher;
import com.ruoyi.common.utils.StringUtils;

/**
 * 大屏免密登录 RSA（PKCS#1）：前端 JSEncrypt 公钥加密 UUID，服务端私钥解密校验。
 */
public final class ScreenLoginRsaSupport
{
    private static final String RSA_TRANSFORMATION = "RSA/ECB/PKCS1Padding";

    private ScreenLoginRsaSupport()
    {
    }

    public static String encrypt(String plainText, String publicKeyBase64)
    {
        if (StringUtils.isEmpty(plainText) || StringUtils.isEmpty(publicKeyBase64))
        {
            throw new IllegalArgumentException("plain/publicKey required");
        }
        try
        {
            Cipher cipher = Cipher.getInstance(RSA_TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, loadPublicKey(publicKeyBase64));
            byte[] cipherBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(cipherBytes);
        }
        catch (Exception ex)
        {
            throw new IllegalStateException("RSA 加密失败", ex);
        }
    }

    public static String decrypt(String cipherTextBase64, String privateKeyBase64)
    {
        if (StringUtils.isEmpty(cipherTextBase64) || StringUtils.isEmpty(privateKeyBase64))
        {
            return null;
        }
        try
        {
            Cipher cipher = Cipher.getInstance(RSA_TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, loadPrivateKey(privateKeyBase64));
            byte[] plainBytes = cipher.doFinal(Base64.getDecoder().decode(cipherTextBase64.trim()));
            return new String(plainBytes, StandardCharsets.UTF_8);
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    static boolean isValidUuid(String text)
    {
        if (StringUtils.isEmpty(text))
        {
            return false;
        }
        try
        {
            UUID.fromString(text.trim());
            return true;
        }
        catch (IllegalArgumentException ex)
        {
            return false;
        }
    }

    static PublicKey loadPublicKey(String publicKeyBase64) throws Exception
    {
        byte[] keyBytes = Base64.getDecoder().decode(normalizeBase64(publicKeyBase64));
        return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes));
    }

    static PrivateKey loadPrivateKey(String privateKeyBase64) throws Exception
    {
        byte[] keyBytes = Base64.getDecoder().decode(normalizeBase64(privateKeyBase64));
        return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    }

    private static String normalizeBase64(String key)
    {
        return key.replaceAll("\\s+", "");
    }
}
