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();  //密码不能用特殊符号
      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("06");

			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, true); 
		/* AIPGSignature signature = new AIPGSignature(AIPGSignature.SM3_SM2, true); */
		String signedStr = null;
		System.out.println(strMsg);
        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{
      AIPGSignature aipgSignature = new AIPGSignature(AIPGSignature.SHA1_RSA, false);
      System.out.println(aipgSignature.signMsg("123", new File("config/user-rsa.p12"), "111111"));
    }
}
