package com.jeequan.jeepay.thirdparty.channel.yspay.utils;

import cfca.sadk.algorithm.common.Mechanism;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.lib.crypto.Session;
import cfca.sadk.util.KeyUtil;
import cfca.sadk.util.Signature;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import java.security.PrivateKey;
import java.util.Map;


@Slf4j
public class SignSmUtil {


    /**
     * 国密算法签名（报文）
     * @param sm2FilePath
     * @param msg
     * @return 返回 256长度base64编码
     * @throws Exception
     */
    public synchronized static String signMsgSM2(String sm2FilePath, String passWord, String msg) throws Exception {
        // 返回的是256位
        byte[] signed;
        try {
            final String deviceName = JCrypto.JSOFT_LIB;
            JCrypto.getInstance().initialize(deviceName, null);
            Session session = JCrypto.getInstance().openSession(deviceName);
            PrivateKey priKey = KeyUtil.getPrivateKeyFromSM2(YspayKit.readFile(sm2FilePath), passWord);
            byte[] sourceData = msg.getBytes();
            Signature util = new Signature();
            String signAlg = Mechanism.SM3_SM2;//SM3WithSM2
            // 签名，必须指定签名算法，返回BASE64签名结果
            signed = util.p1SignMessage(signAlg, sourceData, priKey, session);
        } catch (Exception e) {
            log.error("", e);
            throw new Exception("报文SM2签名失败");
        }
        String checkValue = new String(signed);
        return String.format("%-256s", checkValue);
    }



    /**
     * 异步通知参数验签
     */
    public static boolean asynVerifyYsSm(String sm2FilePath, Map<String, String> reqMap) throws Exception {
        //请用银盛的公钥证书
        //公钥地址
        //获取银盛公钥
        GMCertInfo verifyCertInfo = GMSignUtils.getVerifyCertInfo(sm2FilePath);
        //验签
        String sign = reqMap.get("sign").trim();
        reqMap.remove("sign");
        System.out.println("签名原文:"+reqMap);
        String content = YspayKit.getSignContent(reqMap);
        System.out.println("验签数据"+content+","+sign);
        byte[] srcData = content.getBytes("UTF-8");
        boolean validateSignResult = GMSignUtils.verifyMsgSignSM2(verifyCertInfo, Base64.decodeBase64(sign.getBytes("UTF-8")), srcData);

        return validateSignResult;
    }
}
