package ink.wgink.module.wechat.utils.pay;

import org.bouncycastle.util.encoders.Base64;

import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.security.cert.X509Certificate;

/**
 * @ClassName: PayVerifyUtil
 * @Description: 验证工具
 * @Author: wanggeng
 * @Date: 2021/8/18 11:20 下午
 * @Version: 1.0
 */
public class PayVerifyUtil {
    /**
     * 验证签名
     *
     * @param signature       待验证的签名
     * @param body            应答主体
     * @param nonce           随机串
     * @param timestamp       时间戳
     * @param certInputStream 微信支付平台证书输入流
     * @return
     * @throws Exception
     */
    public static boolean verifySignature(String signature, String body, String nonce, String timestamp, X509Certificate certificate) throws Exception {
        String buildSignMessage = buildSignMessage(timestamp, nonce, body);
        System.out.println("buildSignMessage: " + buildSignMessage);
        // 获取证书
        PublicKey publicKey = certificate.getPublicKey();
        return checkByPublicKey(buildSignMessage, signature, publicKey);
    }

    /**
     * 公钥验证签名
     *
     * @param data      需要加密的数据
     * @param sign      签名
     * @param publicKey 公钥
     * @return
     * @throws Exception
     */
    public static boolean checkByPublicKey(String data, String sign, PublicKey publicKey) throws Exception {
        java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");
        signature.initVerify(publicKey);
        signature.update(data.getBytes(StandardCharsets.UTF_8));
        return signature.verify(Base64.decode(sign.getBytes(StandardCharsets.UTF_8)));
    }

    public static String buildSignMessage(String timestamp, String nonceStr, String body) {
        return new StringBuilder()
                .append(timestamp)
                .append("\n")
                .append(nonceStr)
                .append("\n")
                .append(body)
                .append("\n")
                .toString();
    }

}
