cn.usually.common.pay.union.sdk.SDKUtil.java Source code

Java tutorial

Introduction

Here is the source code for cn.usually.common.pay.union.sdk.SDKUtil.java

Source

/**
 *
 * Licensed Property to China UnionPay Co., Ltd.
 * 
 * (C) Copyright of China UnionPay Co., Ltd. 2010
 *     All Rights Reserved.
 *
 * 
 * Modification History:
 * =============================================================================
 *   Author         Date          Description
 *   ------------ ---------- ---------------------------------------------------
 *   xshu       2014-05-28      MPI
 * =============================================================================
 */
package cn.usually.common.pay.union.sdk;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;

public class SDKUtil {

    protected static char[] letter = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

    protected static final Random random = new Random();

    /**
     * ????
     * 
     * @param url
     *            URL
     * @param data
     *            ???
     * @param httpHeads
     *            HTTP?
     * @param encoding
     *            ?
     * @return 
     */
    public static String send(String url, Map<String, String> data, String encoding, int connectionTimeout,
            int readTimeout) {
        HttpClient hc = new HttpClient(url, connectionTimeout, readTimeout);
        String res = "";
        try {
            int status = hc.send(data, encoding);
            if (200 == status) {
                res = hc.getResult();
            }
        } catch (Exception e) {
            LogUtil.writeErrorLog("", e);
        }
        return res;
    }

    /**
     * ???(SHA1?),
     * 
     * @param data
     *            ???Map?
     * @param encoding
     *            ?
     * @return ????
     */
    public static boolean sign(Map<String, String> data, String encoding) {
        if (isEmpty(encoding)) {
            encoding = "UTF-8";
        }
        // ?????
        data.put(SDKConstants.param_certId, CertUtil.getSignCertId());
        // Map???key1=value1&key2=value2?
        String stringData = coverMap2String(data);
        LogUtil.writeLog("??:[" + stringData + "]");
        /**
         * ??\base64?
         */
        byte[] byteSign = null;
        String stringSign = null;
        try {
            // SHA1?16
            byte[] signDigest = SecureUtil.sha1X16(stringData, encoding);
            byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft(CertUtil.getSignCertPrivateKey(), signDigest));
            stringSign = new String(byteSign);
            // ??
            data.put(SDKConstants.param_signature, stringSign);
            return true;
        } catch (Exception e) {
            LogUtil.writeErrorLog("??", e);
            return false;
        }
    }

    /**
     * ????????????<br>
     * ????
     * 
     * @param data
     *            ???Map?
     * @param encoding
     *            ?
     * @param certPath
     *            ??
     * @param certPwd
     *            ??
     * @return ??
     */
    public static boolean signByCertInfo(Map<String, String> data, String encoding, String certPath,
            String certPwd) {
        if (isEmpty(encoding)) {
            encoding = "UTF-8";
        }
        if (isEmpty(certPath) || isEmpty(certPwd)) {
            LogUtil.writeLog("Invalid Parameter:CertPath=[" + certPath + "],CertPwd=[" + certPwd + "]");
            return false;
        }
        // ?????
        data.put(SDKConstants.param_certId, CertUtil.getCertIdByKeyStoreMap(certPath, certPwd));
        // Map???key1=value1&key2=value2?
        String stringData = coverMap2String(data);
        /**
         * ??\base64?
         */
        byte[] byteSign = null;
        String stringSign = null;
        try {
            byte[] signDigest = SecureUtil.sha1X16(stringData, encoding);
            byteSign = SecureUtil.base64Encode(
                    SecureUtil.signBySoft(CertUtil.getSignCertPrivateKeyByStoreMap(certPath, certPwd), signDigest));
            stringSign = new String(byteSign);
            // ??
            data.put(SDKConstants.param_signature, stringSign);
            return true;
        } catch (Exception e) {
            LogUtil.writeErrorLog("??", e);
            return false;
        }
    }

    /**
     * ???(SHA-1?)
     * 
     * @param resData
     *            ?
     * @param encoding
     *            ??
     * @return
     */
    public static boolean validate(Map<String, String> resData, String encoding) {
        LogUtil.writeLog("?");
        if (isEmpty(encoding)) {
            encoding = "UTF-8";
        }
        String stringSign = resData.get(SDKConstants.param_signature);

        // ?certId ????Map?
        String certId = resData.get(SDKConstants.param_certId);

        LogUtil.writeLog("??[" + certId + "]");

        // Map???key1=value1&key2=value2?
        String stringData = coverMap2String(resData);

        LogUtil.writeLog("[" + stringData + "]");

        try {
            // ???????.
            return SecureUtil.validateSignBySoft(CertUtil.getValidateKey(certId),
                    SecureUtil.base64Decode(stringSign.getBytes(encoding)),
                    SecureUtil.sha1X16(stringData, encoding));
        } catch (UnsupportedEncodingException e) {
            LogUtil.writeErrorLog(e.getMessage(), e);
        } catch (Exception e) {
            LogUtil.writeErrorLog(e.getMessage(), e);
        }
        return false;
    }

    /**
     * Map???key1=value1&key2=value2? ????signature
     * 
     * @param data
     *            Map?
     * @return ?
     */
    public static String coverMap2String(Map<String, String> data) {
        TreeMap<String, String> tree = new TreeMap<String, String>();
        Iterator<Entry<String, String>> it = data.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            if (SDKConstants.param_signature.equals(en.getKey().trim())) {
                continue;
            }
            tree.put(en.getKey(), en.getValue());
        }
        it = tree.entrySet().iterator();
        StringBuffer sf = new StringBuffer();
        while (it.hasNext()) {
            Entry<String, String> en = it.next();
            sf.append(en.getKey() + SDKConstants.EQUAL + en.getValue() + SDKConstants.AMPERSAND);
        }
        return sf.substring(0, sf.length() - 1);
    }

    /**
     * ? key=value&key=value?Map
     * 
     * @param result
     * @return
     */
    public static Map<String, String> coverResultString2Map(String result) {
        return convertResultStringToMap(result);
    }

    /**
     * key=value&key=value?Map
     * 
     * @param result
     * @return
     */
    public static Map<String, String> convertResultStringToMap(String result) {
        Map<String, String> map = null;
        try {

            if (StringUtils.isNotBlank(result)) {
                if (result.startsWith("{") && result.endsWith("}")) {
                    System.out.println(result.length());
                    result = result.substring(1, result.length() - 1);
                }
                map = parseQString(result);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * ???
     * 
     * @param str
     *            ??
     * @return ?map
     * @throws UnsupportedEncodingException
     */
    public static Map<String, String> parseQString(String str) throws UnsupportedEncodingException {

        Map<String, String> map = new HashMap<String, String>();
        int len = str.length();
        StringBuilder temp = new StringBuilder();
        char curChar;
        String key = null;
        boolean isKey = true;
        boolean isOpen = false;//
        char openName = 0;
        if (len > 0) {
            for (int i = 0; i < len; i++) {// ???
                curChar = str.charAt(i);// ??
                if (isKey) {// ??key

                    if (curChar == '=') {// ?= 
                        key = temp.toString();
                        temp.setLength(0);
                        isKey = false;
                    } else {
                        temp.append(curChar);
                    }
                } else {// ??value
                    if (isOpen) {
                        if (curChar == openName) {
                            isOpen = false;
                        }

                    } else {//?
                        if (curChar == '{') {//?
                            isOpen = true;
                            openName = '}';
                        }
                        if (curChar == '[') {
                            isOpen = true;
                            openName = ']';
                        }
                    }
                    if (curChar == '&' && !isOpen) {// ?&,??map
                        putKeyValueToMap(temp, isKey, key, map);
                        temp.setLength(0);
                        isKey = true;
                    } else {
                        temp.append(curChar);
                    }
                }

            }
            putKeyValueToMap(temp, isKey, key, map);
        }
        return map;
    }

    private static void putKeyValueToMap(StringBuilder temp, boolean isKey, String key, Map<String, String> map)
            throws UnsupportedEncodingException {
        if (isKey) {
            key = temp.toString();
            if (key.length() == 0) {
                throw new RuntimeException("QString format illegal");
            }
            map.put(key, "");
        } else {
            if (key.length() == 0) {
                throw new RuntimeException("QString format illegal");
            }
            map.put(key, temp.toString());
        }
    }

    /**
     * ?.
     * 
     * @param card
     *            ??
     * @param pwd
     *            ?
     * @param encoding
     *            ?
     * @return ?
     */
    public static String encryptPin(String card, String pwd, String encoding) {
        return SecureUtil.EncryptPin(pwd, card, encoding, CertUtil.getEncryptCertPublicKey());
    }

    /**
     * CVN2.
     * 
     * @param cvn2
     *            CVN2
     * @param encoding
     *            ?
     * @return ??
     */
    public static String encryptCvn2(String cvn2, String encoding) {
        return SecureUtil.EncryptData(cvn2, encoding, CertUtil.getEncryptCertPublicKey());
    }

    /**
     * CVN2
     * 
     * @param base64cvn2
     *            ?CVN2
     * @param encoding
     *            ?
     * @return ??
     */
    public static String decryptCvn2(String base64cvn2, String encoding) {
        return SecureUtil.DecryptedData(base64cvn2, encoding, CertUtil.getSignCertPrivateKey());
    }

    /**
     * .
     * 
     * @param date
     *            
     * @param encoding
     *            ?
     * @return ??
     */
    public static String encryptAvailable(String date, String encoding) {
        return SecureUtil.EncryptData(date, encoding, CertUtil.getEncryptCertPublicKey());
    }

    /**
     * .
     * 
     * @param base64Date
     *            
     * @param encoding
     *            ?
     * @return ??
     */
    public static String decryptAvailable(String base64Date, String encoding) {
        return SecureUtil.DecryptedData(base64Date, encoding, CertUtil.getSignCertPrivateKey());
    }

    /**
     * ??.
     * 
     * @param pan
     *            ??
     * @param encoding
     *            ?
     * @return ???
     */
    public static String encryptPan(String pan, String encoding) {
        return SecureUtil.EncryptData(pan, encoding, CertUtil.getEncryptCertPublicKey());
    }

    /**
     * ??.
     * 
     * @param base64Pan
     *            ????
     * @param encoding
     * @return
     */
    public static String decryptPan(String base64Pan, String encoding) {
        return SecureUtil.DecryptedData(base64Pan, encoding, CertUtil.getSignCertPrivateKey());
    }

    /**
     * ??encryptedInfo
     * 
     * @param date
     *            
     * @param encoding
     *            ?
     * @return ??
     */
    public static String encryptEpInfo(String encryptedInfo, String encoding) {
        return SecureUtil.EncryptData(encryptedInfo, encoding, CertUtil.getEncryptCertPublicKey());
    }

    /**
     * ??encryptedInfo.
     * 
     * @param base64Date
     *            
     * @param encoding
     *            ?
     * @return ??
     */
    public static String decryptEpInfo(String base64EncryptedInfo, String encoding) {
        return SecureUtil.DecryptedData(base64EncryptedInfo, encoding, CertUtil.getSignCertPrivateKey());
    }

    /**
     * ???
     * 
     * @param trackData
     *            ???
     * @param encoding
     *            ??
     * @return String
     */
    public static String encryptTrack(String trackData, String encoding) {
        return SecureUtil.EncryptData(trackData, encoding, CertUtil.getEncryptTrackCertPublicKey());
    }

    /**
     * ???
     * 
     * @param trackData
     *            ???
     * @param encoding
     *            ??
     * @param modulus
     *            
     * @param exponent
     *            
     * @return
     */
    public static String encryptTrack(String trackData, String encoding, String modulus, String exponent) {
        return SecureUtil.EncryptData(trackData, encoding,
                CertUtil.getEncryptTrackCertPublicKey(modulus, exponent));
    }

    /**
     * ?NULL
     * 
     * @param s
     *            ?
     * @return  true- false-?
     */
    public static boolean isEmpty(String s) {
        return null == s || "".equals(s.trim());
    }

    /**
     * ????YYYYMMDDhhmmss
     * 
     * @return YYYYMMDDhhmmss?
     */
    public static String generateTxnTime() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    /**
     * ??AN12..32
     * 
     * @return
     */
    public static String generateOrderId() {
        StringBuilder sb = new StringBuilder();
        int len = random.nextInt(18);
        for (int i = 0; i < len; i++) {
            sb.append(letter[i]);
        }
        return generateTxnTime() + sb.toString();
    }

    /**
     * HTML?,?form?(??)
     * 
     * @param url
     * @param data
     * @return
     */
    public static String createAutoSubmitForm(String url, Map<String, String> data) {
        StringBuffer sf = new StringBuffer();
        sf.append("<form id = \"sform\" action=\"" + url + "\" method=\"post\">");
        if (null != data && 0 != data.size()) {
            Set<Entry<String, String>> set = data.entrySet();
            Iterator<Entry<String, String>> it = set.iterator();
            while (it.hasNext()) {
                Entry<String, String> ey = it.next();
                String key = ey.getKey();
                String value = ey.getValue();
                sf.append(
                        "<input type=\"hidden\" name=\"" + key + "\" id=\"" + key + "\" value=\"" + value + "\"/>");
            }
        }
        sf.append("</form>");
        sf.append("</body>");
        sf.append("<script type=\"text/javascript\">");
        sf.append("document.getElementById(\"sform\").submit();\n");
        sf.append("</script>");
        return sf.toString();
    }

    public static void main(String[] args) {
        System.out.println(SDKUtil.encryptTrack("12", "utf-8"));
    }

}