package com.cnd3b.utility.wechatpay.apppay.POJO;

import com.cnd3b.utility.Encryption;
import com.cnd3b.utility.wechatpay.apppay.parameter;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;

import java.security.MessageDigest;
import java.util.Calendar;
import java.util.Iterator;

public class Base {

    /**
     * 生成签名
     *
     * @param xml
     */
    protected void createSign(DOMElement xml) {
        Iterator<Element> it = xml.elementIterator();
        StringBuffer A = new StringBuffer();
        while (it.hasNext()) {
            Element element = it.next();
            A.append(element.getName()).append("=").append(element.getText()).append("&");
        }
        A.append("key=").append(parameter.key);
        xml.addElement("sign").addText(MD5Encode(A.toString(), "UTF-8").toUpperCase());
    }
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (byte value : b) {
            resultSb.append(byteToHexString(value));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return resultString;
    }

    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};


    /**
     * 生成随机字符串
     *
     * @return
     */
    protected String createNonce_str(String str) {
        return new Encryption().Encode_MD5(str + Calendar.getInstance().getTimeInMillis()).substring(0, 30);
    }
}
