package com.allinpay.demo.util;

import java.io.File;
import java.security.Provider;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.allinpay.demo.AIPGException;
import com.allinpay.demo.DemoConfig;
import com.allinpay.demo.xstruct.common.InfoReq;

/**
 * @Description
 * @Author meixf@allinpay.com
 * @Date 2018年5月24日
 **/
public class DemoUtil {
	public static Provider prvd = null;

	static{
//	    System.out.println("初始化BC"  +  System.getProperty("addprovider"));
		prvd = new BouncyCastleProvider();  //密码不能用特殊符号
		if("true".equals(System.getProperty("addprovider")) && Security.getProvider("BC") == null){
		    System.out.println("未找到·");
		    Security.addProvider(prvd);
		}
	}

	public static InfoReq makeReq(String trxcod){
		InfoReq info=new InfoReq();
		info.setTRX_CODE(trxcod);
		info.setREQ_SN(DemoConfig.merchantid + String.format("-%016d",System.currentTimeMillis()));
		info.setUSER_NAME(DemoConfig.username);
		info.setUSER_PASS(DemoConfig.userpass);
		info.setLEVEL("5");
		info.setDATA_TYPE("2");
		info.setVERSION("03");
	    info.setMERCHANT_ID(DemoConfig.merchantid);

		return info;
	}

	public static String getNow(){
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		return df.format(new Date());
	}

	public static String getRandomString(int length) {
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
		Random random = new Random();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * @param xmlMsg   待签名报文
	 * @param pathPfx
	 * @param pass
	 * @return  签名后的报文
	 * @throws AIPGException
	 */
	public static String buildSignedXml(String xmlMsg) throws AIPGException{
		if(xmlMsg == null){
			throw new AIPGException("传入的加签报文为空");
		}
		String IDD_STR="<SIGNED_MSG></SIGNED_MSG>";
		if(xmlMsg.indexOf(IDD_STR) == -1){
			throw new AIPGException("找不到签名信息字段");
		}
		String strMsg = xmlMsg.replaceAll(IDD_STR, "");
		AIPGSignature signature = new AIPGSignature(AIPGSignature.SHA1_RSA, false);
		/*AIPGSignature signature = new AIPGSignature(AIPGSignature.SM3_SM2, true);*/
		String signedStr = null;
        try {
            signedStr = signature.signMsg(strMsg, new File(DemoConfig.pathpfx), DemoConfig.pfxpass);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AIPGException("3999", "签名失败");
        }
		String strRnt = xmlMsg.replaceAll(IDD_STR, "<SIGNED_MSG>" + signedStr + "</SIGNED_MSG>");
		return strRnt;
	}

	/**
	 * @param xmlMsg  返回报文
	 * @param pathCer  通联公钥
	 * @return
	 * @throws AIPGException
	 */
	public static boolean verifyXml(String xmlMsg) throws AIPGException{
		if(xmlMsg == null){
			throw new AIPGException("传入的验签报文为空");
		}
		int pre = xmlMsg.indexOf("<SIGNED_MSG>");
		int suf = xmlMsg.indexOf("</SIGNED_MSG>");
		if(pre == - 1 || suf == -1 || pre >= suf){
			throw new AIPGException("找不到签名信息");
		}
		String signedStr = xmlMsg.substring(pre + 12, suf);
		String msgStr = xmlMsg.substring(0, pre) + xmlMsg.substring(suf + 13);
		AIPGSignature signature = new AIPGSignature(AIPGSignature.SHA1_RSA, false);
	/*	AIPGSignature signature = new AIPGSignature(AIPGSignature.SM3_SM2, true);//国密
*/		try {
            return signature.verifyMsg(signedStr, msgStr, new File(DemoConfig.pathcer));
        } catch (Exception e) {
            e.printStackTrace();
            throw new AIPGException("3999", "验签失败");
        }
	}

    public static void main(String[] args) throws Exception{
        String xmlMsg = "<AIPG><INFO><TRX_CODE>100007</TRX_CODE><VERSION>04</VERSION><DATA_TYPE>2</DATA_TYPE><LEVEL>5</LEVEL><USER_NAME>20010000002266704</USER_NAME><USER_PASS>111111</USER_PASS><REQ_SN>51108202003183515188738223401682</REQ_SN><SIGNED_MSG>456ae65e9835afc3b3b861929338739cfb77635f7edde7fcb243546da54810155cc9f39c9de34dbd8fa648f9b8595bf55dd5a7066396509634bc15883a42f759b59e7e063b82e0be327c4abab0e28e33e5d4e52ab8c000da8ae7dda041fbb6e5a75ce3fde1a180a48a37fd5400bb48e6628312058ac98bbf0ced10444a7c1dc0</SIGNED_MSG></INFO><TRANSFER><MERCHANT_ID>200100000022667</MERCHANT_ID><SUBMIT_TIME>20200318223401</SUBMIT_TIME><ACCOUNT_NAME>资恩明</ACCOUNT_NAME><AMOUNT>87331</AMOUNT><CURRENCY></CURRENCY><BUSINESS_CODE>09300</BUSINESS_CODE><FROM_ACCOUNT_NO>6228481198640739075</FROM_ACCOUNT_NO><TO_ACCOUNT_NO>6226009907170522</TO_ACCOUNT_NO><REMARK>873316228481</REMARK></TRANSFER></AIPG>";
        System.out.println(verifyXml(xmlMsg));
    }
}
