package org.shop.crop;

import javax.crypto.Cipher;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

/**
 * @description 加解密工具
 * @date 2024/11/21 9:22
 */
public class EncodeUtils {

    public static PrivateKey getPrivateKey(String privKeyPEM) throws Exception {
        String pem = privKeyPEM.trim();
        // 清理头尾和空白
      if (pem.contains("BEGIN PRIVATE KEY")) {
            // PKCS#8 格式（使用 URL-safe Base64）
            pem = pem
                    .replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");
        } else {
            throw new IllegalArgumentException("Invalid private key format");
        }
        System.out.println("Raw private key: " + pem);

        // 关键：使用 url decoder！
        byte[] derBytes = Base64.getDecoder().decode(pem);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        // PKCS#8
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(derBytes);
        return keyFactory.generatePrivate(spec);
    }

    // ✅ 修复命名和字符集
    public static String decryptRandomKey(String encryptedRandomKeyBase64, String privateKeyPem) throws Exception {
        PrivateKey privateKey = getPrivateKey(privateKeyPem);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedRandomKeyBase64);;
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes, StandardCharsets.UTF_8); // 显式指定 UTF-8
    }

}