package cn.qg.qaplatform.mock.encrypt.paycenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


import java.util.Map.Entry;
import java.util.TreeMap;

@Slf4j
public class EncryUtil {

  /**
   * 生成RSA签名
   */
  public static String handleRSA(TreeMap<String, Object> map,
      String privateKey) {
    StringBuffer sbuffer = new StringBuffer();
    for (Entry<String, Object> entry : map.entrySet()) {
      sbuffer.append(entry.getValue());
    }
    String signTemp = sbuffer.toString();

    String sign = "";
    if (StringUtils.isNotEmpty(privateKey)) {
      sign = Rsa.sign(signTemp, privateKey);
    }
    return sign;
  }

  /**
   * 对易宝支付返回的结果进行验签
   *
   * @param data 易宝支付返回的业务数据密文
   * @param encrypt_key 易宝支付返回的对ybAesKey加密后的密文
   * @param yibaoPublickKey 易宝支付提供的公钥
   * @param merchantPrivateKey 商户自己的私钥
   * @return 验签是否通过
   * @throws Exception
   */
  public static boolean checkDecryptAndSign(String data, String encrypt_key,
      String yibaoPublickKey, String merchantPrivateKey) {

    /** 1.使用YBprivatekey解开aesEncrypt。 */
    String AESKey;
    try {
      AESKey = Rsa.decrypt(encrypt_key, merchantPrivateKey);
    } catch (Exception e) {
      /** AES密钥解密失败 */
      log.error("{}", e);
      return false;
    }

    /** 2.用aeskey解开data。取得data明文 */
    String realData = Aes.decryptFromBase64(data, AESKey);

    TreeMap<String, String> map = JSON.parseObject(realData,
        new TypeReference<TreeMap<String, String>>() {
        });

    /** 3.取得data明文sign。 */
    String sign = StringUtils.trimToEmpty(map.get("sign"));

    StringBuilder signData = new StringBuilder();
    for (Entry<String, String> entry : map.entrySet()) {
      if (StringUtils.equals(entry.getKey(), "sign")) {
        continue;
      }
      signData.append(entry.getValue() == null ? "" : entry.getValue());
    }

    /** 5. result为true时表明验签通过 */
    String str = signData.toString();

    return Rsa.checkSign(str, sign,
        yibaoPublickKey);
  }
}
