package com.fastbee.common.utils.pay;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    /**
     * 验签方法---微信公钥
     * @param wechatpaySignature Wechatpay-Signature 响应头中的签名
     * @param wechatpayTimestamp Wechatpay-Timestamp 响应头中的时间戳
     * @param wechatpayNonce Wechatpay-Nonce 响应头中的随机串
     * @param responseBody 应答报文主体
     * @param publicKey 微信支付公钥（PEM 格式，去掉头尾并解码为二进制）
     * @return 是否验签成功
     * @throws Exception
     */
    public static boolean verifySignature(String wechatpaySignature,
                                          String wechatpayTimestamp,
                                          String wechatpayNonce,
                                          String responseBody,
                                          String publicKey) throws Exception {
        // 构造验签名串：应答时间戳\n应答随机串\n应答报文主体\n
        String message = wechatpayTimestamp + "\n" +
                wechatpayNonce + "\n" +
                responseBody + "\n";

        // 解码微信支付公钥（Base64 格式）
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey rsaPublicKey = keyFactory.generatePublic(keySpec);

        // 初始化 Signature 对象，指定算法为 SHA256withRSA
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(rsaPublicKey);

        // 更新验签名串
        signature.update(message.getBytes(StandardCharsets.UTF_8));

        // 验证签名
        byte[] signatureBytes = Base64.getDecoder().decode(wechatpaySignature);
        return signature.verify(signatureBytes);
    }



    /**
     * 验签方法---平台证书
     * @param wechatpaySignature Wechatpay-Signature 响应头中的签名
     * @param wechatpayTimestamp Wechatpay-Timestamp 响应头中的时间戳
     * @param wechatpayNonce Wechatpay-Nonce 响应头中的随机串
     * @param responseBody 应答报文主体
     * @param publicKey 微信支付公钥（PEM 格式，去掉头尾并解码为二进制）
     * @return 是否验签成功
     * @throws Exception
     */
    public static boolean verifySignatureByCertificate(String wechatpaySignature,
                                          String wechatpayTimestamp,
                                          String wechatpayNonce,
                                          String responseBody,
                                          String publicKey) throws Exception {
        // 构造验签名串：应答时间戳\n应答随机串\n应答报文主体\n
        String message = wechatpayTimestamp + "\n" +
                wechatpayNonce + "\n" +
                responseBody + "\n";

        // 解码微信支付公钥（Base64 格式）
        byte[] certBytes = Base64.getDecoder().decode(publicKey);
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certBytes));
        PublicKey rsaPublicKey = certificate.getPublicKey();

        // 初始化 Signature 对象，指定算法为 SHA256withRSA
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(rsaPublicKey);

        // 更新验签名串
        signature.update(message.getBytes(StandardCharsets.UTF_8));

        // 验证签名
        byte[] signatureBytes = Base64.getDecoder().decode(wechatpaySignature);
        return signature.verify(signatureBytes);
    }

}
