package com.huimv.employment.common.util;

import com.huimv.employment.common.exception.BizException;
import com.huimv.employment.common.exception.ErrorCode;

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

/**
 * RSA 密码解密（与前端 JSEncrypt PKCS#1 v1.5 兼容）。
 */
public final class RsaUtils {

    private static final String RSA = "RSA";
    private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";

    private RsaUtils() {
    }

    /**
     * 使用 PKCS#8 Base64 私钥解密前端提交的密文（Base64）。
     */
    public static String decryptByPrivateKey(String base64CipherText, String base64Pkcs8PrivateKey) {
        if (base64CipherText == null || base64CipherText.trim().isEmpty()) {
            throw new BizException(ErrorCode.BAD_REQUEST, "密码不能为空");
        }
        if (base64Pkcs8PrivateKey == null || base64Pkcs8PrivateKey.trim().isEmpty()) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, "RSA 私钥未配置");
        }
        try {
            byte[] keyBytes = Base64.getDecoder().decode(stripPem(base64Pkcs8PrivateKey));
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PrivateKey privateKey = keyFactory.generatePrivate(spec);

            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] plainBytes = cipher.doFinal(Base64.getDecoder().decode(base64CipherText.trim()));
            return new String(plainBytes, StandardCharsets.UTF_8);
        } catch (BizException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new BizException(ErrorCode.BAD_REQUEST, "密码解密失败，请刷新页面后重试");
        }
    }

    private static String stripPem(String key) {
        return key.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                .replace("-----END RSA PRIVATE KEY-----", "")
                .replaceAll("\\s", "");
    }
}
