package org.tio.sitexxx.service.service.pay.utils.ncount;

import org.tio.sitexxx.service.service.pay.exception.NCountException;
import org.tio.sitexxx.service.service.pay.utils.HexStringByte;

import java.security.PrivateKey;
import java.util.Base64;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-11-26 11:37
 *    desc   :
 * </pre>
 */
public class NCountSign {
    /**
     * 签名
     *
     *            企业用户编号
     * @param merData
     *            明文串
     *            交易类型 0--收款交易 1--付款交易 2--辅助类交易
     * @return 签名后的消息
     * @throws NCountException
     */
    public static byte[] sign(PrivateKey privateKey, String merData) throws NCountException {

        try {
            return NCountRSAAlgorithms.sign(privateKey, merData);
        } catch (Exception e) {
            throw new NCountException("100F1002", "读取密钥异常", e);
        }

    }

    /**
     * 验证签名
     *
     * @param merData
     *            明文串
     * @param signMsg
     *            签名消息
     * @return 验证签名的结果 true--成功 false--失败
     * @throws NCountException
     */
    public static boolean verify(String merData, String signMsg) throws NCountException {
        boolean result;
        String hexPublicKey = HexStringByte.byteToHex(Base64.getDecoder().decode(NCountKey.NCOUNT_PUBLIC_KEY));
        String signVal = HexStringByte.byteToHex(Base64.getDecoder().decode(signMsg));
        result = verifySignatureByRSA(merData, signVal, "UTF-8", hexPublicKey);
        return result;
    }

    /**
     * @param src
     * @param dit
     * @param charsetType
     * @param publicKey
     * @return
     * @throws NCountException
     */
    private static boolean verifySignatureByRSA(String src, String dit, String charsetType, String publicKey) throws NCountException {
        if ((src == null) || ("".equals(src.trim()))) {
            throw new NCountException("src is empty ,verifySignatureByRSA无法执行");
        }
        if ((dit == null) || ("".equals(dit.trim()))) {
            throw new NCountException("dit is empty ,verifySignatureByRSA无法执行");
        }
        try {
            return NCountRSAAlgorithms.verify(publicKey, src, dit);
        } catch (Exception e) {
            e.printStackTrace();
            throw new NCountException("验证签名出现异常：请检查输入参数", e.getMessage());
        }
    }
}
