package com.hzs.third.pay.controller.base;

import com.hzs.common.core.web.controller.BaseController;
import com.hzs.third.pay.util.baofu.FormatUtil;
import com.hzs.third.pay.util.baofu.RsaCodingUtil;
import com.hzs.third.pay.util.baofu.SecurityUtil;
import com.hzs.third.pay.util.baofu.SignatureUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.TreeMap;

/**
 * 支付基础控制器
 */
@Slf4j
public class PayBaseController extends BaseController {

    /**
     * 生成签名
     *
     * @param params
     * @param pfxPath
     * @param pfxPwd
     * @return
     * @throws Exception
     */
    protected String createBaoFuSign(TreeMap<String, Object> params, String pfxPath, String pfxPwd) throws Exception {
        // 拼装参数
        String signStr = FormatUtil.coverObjectMap2String(params);
        // 签名
        String signature = SecurityUtil.sha1X16(signStr, "UTF-8");
        // 加密签名
        return SignatureUtils.encryptByRSA(signature, pfxPath, pfxPwd);
    }

    /**
     * 返回处理签名
     *
     * @param param
     * @return
     * @throws Exception
     */
    protected String returnBaoFuSign(TreeMap<String, String> param) throws Exception {
        // 拼接参数
        String RSignVStr = FormatUtil.coverMap2String(param);
        // 加密生成签名域
        return SecurityUtil.sha1X16(RSignVStr, "UTF-8");
    }

    /**
     * 根据数据信封解密数据
     *
     * @param dgtlEnvlp
     * @param pfxPath
     * @param pfxPwd
     * @param content
     * @return
     * @throws Exception
     */
    protected String getBaoFuDgtlEnvlpContent(String dgtlEnvlp, String pfxPath, String pfxPwd, String content) throws Exception {
        String rDgtlEnvlp = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPriPfxFile(dgtlEnvlp, pfxPath, pfxPwd));
        String rAesKey = FormatUtil.getAesKey(rDgtlEnvlp);
        log.error("宝付数据信封加密key: {}", rAesKey);
        return SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(content, rAesKey));
    }

}
