package com.table.transfer.util.encryp;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Slf4j

public class RSAEncryptionUtil {

    public static void a() {
        try {
            System.out.println("开始初始化 Bouncy Castle...");
            System.out.println("Java 版本: " + System.getProperty("java.version"));
            System.out.println("Java Home: " + System.getProperty("java.home"));

            // 列出所有已注册的安全提供者
            Provider[] providers = Security.getProviders();
            System.out.println("当前安全提供者:");
            for (Provider provider : providers) {
                System.out.println(" - " + provider.getName() + " v" + provider.getVersion());
            }

            // 检查BC是否已存在 - 这里修改：不移除，直接使用现有的
            Provider existingBC = Security.getProvider("BC");
            if (existingBC != null) {
                System.out.println("发现已存在的 BC 提供者: " + existingBC.getInfo());
                // 不移除，直接使用现有的BC提供者
                System.out.println("使用现有的 BC 提供者");
            } else {
                // 添加新的BC提供者
                BouncyCastleProvider newProvider = new BouncyCastleProvider();
                Security.addProvider(newProvider);
                System.out.println("成功添加 Bouncy Castle 提供者: " + newProvider.getInfo());
            }

            // 验证BC提供者
            Provider verifiedBC = Security.getProvider("BC");
            if (verifiedBC != null) {
                System.out.println("BC 提供者验证成功: " + verifiedBC.getName());
            } else {
                System.err.println("BC 提供者验证失败!");
            }

            System.out.println("=== 开始加密测试 ===");

            // 测试加密 - 添加更详细的错误处理
            try {
                String testText = "尝试进行加密";
                System.out.println("加密原文: " + testText);

                String encrypted = encrypt(testText);
                System.out.println("加密成功，结果: " + encrypted);
                log.info("加密后: " + encrypted);

                System.out.println("=== 开始解密测试 ===");
                String decrypted = decrypt(encrypted);
                System.out.println("解密成功，结果: " + decrypted);

                boolean match = testText.equals(decrypted);
                System.out.println("加解密验证: " + (match ? "成功" : "失败"));

            } catch (Exception cryptoException) {
                System.err.println("加解密操作失败:");
                cryptoException.printStackTrace();
                log.error("加解密操作失败", cryptoException);

                // 输出更详细的错误信息
                System.err.println("错误类型: " + cryptoException.getClass().getName());
                System.err.println("错误信息: " + cryptoException.getMessage());

                // 检查公钥
                try {
                    byte[] publicKeyBytes = Base64.getDecoder().decode(pubk);
                    System.out.println("公钥长度: " + publicKeyBytes.length + " bytes");

                    // 尝试解析公钥
                    PublicKey publicKey = getPublicKey(publicKeyBytes);
                    System.out.println("公钥算法: " + publicKey.getAlgorithm());
                    System.out.println("公钥格式: " + publicKey.getFormat());
                } catch (Exception keyException) {
                    System.err.println("公钥解析失败:");
                    keyException.printStackTrace();
                }
            }
            System.out.println("没有异常");
        } catch (Exception e) {
            System.err.println("RSA初始化失败:");
            e.printStackTrace();
            log.error("RSA初始化失败", e);
        }

    }


    //todo -d解密
    private static String PK =
            "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDAf2lhRMQC8xK529AiMnTXbFHXvDRT5AIhCSHRFqczqhfxIRanuZ0G3+kz0Leqrqom50XuIsi0jcUMoHbB9hgbg1GnuWtHgxTWtP9uxZiGF6++KhWP/XYgpsZYPcRtNc1W/P71wyfX8VHsBDQqbEoi3hTXJyVG4lClnk4mtAUAO+6+PeUsScUC0Pg2kdYKaPtVvlszLEQhFrIkK0YI021DIZEoyAOw87ncbkS77ekxu9dSwvcGo3dW/ggulhQv8LLgshEWBL1oH1VgC6vDjG/skkkIg416GIsRZ5BtQlVzlmxY3hLQGs8CoXhdTa5zTT+rpDy135pBF6k99KJ28/JjAgMBAAECggEABoKf5U2fQOe85qpEkpOBuzNoXHYdp01mtWVQq4/lYzIyel1/er32B9qsC5UHC1h0XC4aXuZqcUu0shRa230CkJ9Hhci6wrvwFMHEU5gaSUU8WnDpvlIbs0eK17snDT3D8UDuduHlx7R+ST5U+JfIb4tyskMDHdKwtY2VJiSr7M7cgFslAhvDhzyeJxMKZ0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H9pYUTEAvMSudvQIjJ012xR17w0U+QCIQkh0RanM6oX8SEWp7mdBt/pM9C3qq6qJudF7iLItI3FDKB2wfYYG4NRp7lrR4MU1rT/bsWYhhevvioVj/12IKbGWD3EbTXNVvz+9cMn1/FR7AQ0KmxKIt4U1yclRuJQpZ5OJrQFADvuvj3lLEnFAtD4NpHWCmj7Vb5bMyxEIRayJCtGCNNtQyGRKMgDsPO53G5Eu+3pMbvXUsL3BqN3Vv4ILpYUL/Cy4LIRFgS9aB9VYAurw4xv7JJJCIONehiLEWeQbUJVc5ZsWN4S0BrPAqF4XU2uc00/q6Q8td+aQRepPfSidvPyYwIDAQAB";
    private static final String ALGORITHM = "RSA";
    // 必须显式指定 SHA-256，且强制使用 Bouncy Castle

    // 使用系统默认提供者，不指定BC
    private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";

    /**
     * 使用公钥加密数据 - 使用系统默认提供者
     */
    public static String encrypt(String plainText) throws Exception {
        try {
            System.out.println("开始加密，使用系统默认提供者");

            byte[] publicKeyBytes = Base64.getDecoder().decode(pubk);
            PublicKey publicKey = getPublicKey(publicKeyBytes);

            // 关键修改：不使用"BC"，让系统选择默认提供者
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(java.nio.charset.StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);

        } catch (Exception e) {
            throw new Exception("加密失败: " + e.getMessage(), e);
        }
    }

    /**
     * 使用私钥解密数据 - 使用系统默认提供者
     */
    public static String decrypt(String encryptedData) throws Exception {
        try {
            byte[] privateKeyBytes = Base64.getDecoder().decode(PK);
            PrivateKey privateKey = getPrivateKey(privateKeyBytes);

            // 关键修改：不使用"BC"
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, java.nio.charset.StandardCharsets.UTF_8);

        } catch (Exception e) {
            throw new Exception("解密失败: " + e.getMessage(), e);
        }
    }

    private static PublicKey getPublicKey(byte[] keyBytes) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        // 关键修改：不使用"BC"
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(spec);
    }

    private static PrivateKey getPrivateKey(byte[] keyBytes) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        // 关键修改：不使用"BC"
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(spec);
    }

    /**
     * 生成 RSA 密钥对（2048 位）
     */
    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, "BC");
        keyPairGenerator.initialize(2048, new SecureRandom());
        return keyPairGenerator.generateKeyPair();
    }

    public static String getPublicKeyBase64(KeyPair keyPair) {
        return Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
    }

    public static String getPrivateKeyBase64(KeyPair keyPair) {
        return Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
    }

}