ソースを参照

合利宝相关

zhijiezhao 3 年 前
コミット
e193f28bec

+ 476 - 0
src/main/java/com/caimei365/order/utils/helipay/Base64.java

@@ -0,0 +1,476 @@
+package com.caimei365.order.utils.helipay;
+
+import java.io.UnsupportedEncodingException;
+
+public class Base64 {
+	
+	public static void main(String[] args) {
+		
+	}
+    /**
+     * Chunk size per RFC 2045 section 6.8.
+     *
+     * <p>The {@value} character limit does not count the trailing CRLF, but counts
+     * all other characters, including any equal signs.</p>
+     *
+     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
+     */
+    static final int CHUNK_SIZE = 76;
+
+    /**
+     * Chunk separator per RFC 2045 section 2.1.
+     *
+     * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
+     */
+    static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
+
+    /**
+     * The base length.
+     */
+    static final int BASELENGTH = 255;
+
+    /**
+     * Lookup length.
+     */
+    static final int LOOKUPLENGTH = 64;
+
+    /**
+     * Used to calculate the number of bits in a byte.
+     */
+    static final int EIGHTBIT = 8;
+
+    /**
+     * Used when encoding something which has fewer than 24 bits.
+     */
+    static final int SIXTEENBIT = 16;
+
+    /**
+     * Used to determine how many bits data contains.
+     */
+    static final int TWENTYFOURBITGROUP = 24;
+
+    /**
+     * Used to get the number of Quadruples.
+     */
+    static final int FOURBYTE = 4;
+
+    /**
+     * Used to test the sign of a byte.
+     */
+    static final int SIGN = -128;
+
+    /**
+     * Byte used to pad output.
+     */
+    static final byte PAD = (byte) '=';
+
+    // Create arrays to hold the base64 characters and a
+    // lookup for base64 chars
+    private static byte[] base64Alphabet = new byte[BASELENGTH];
+    private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
+
+    // Populating the lookup and character arrays
+    static {
+        for (int i = 0; i < BASELENGTH; i++) {
+            base64Alphabet[i] = (byte) -1;
+        }
+        for (int i = 'Z'; i >= 'A'; i--) {
+            base64Alphabet[i] = (byte) (i - 'A');
+        }
+        for (int i = 'z'; i >= 'a'; i--) {
+            base64Alphabet[i] = (byte) (i - 'a' + 26);
+        }
+        for (int i = '9'; i >= '0'; i--) {
+            base64Alphabet[i] = (byte) (i - '0' + 52);
+        }
+
+        base64Alphabet['+'] = 62;
+        base64Alphabet['/'] = 63;
+
+        for (int i = 0; i <= 25; i++) {
+            lookUpBase64Alphabet[i] = (byte) ('A' + i);
+        }
+
+        for (int i = 26, j = 0; i <= 51; i++, j++) {
+            lookUpBase64Alphabet[i] = (byte) ('a' + j);
+        }
+
+        for (int i = 52, j = 0; i <= 61; i++, j++) {
+            lookUpBase64Alphabet[i] = (byte) ('0' + j);
+        }
+
+        lookUpBase64Alphabet[62] = (byte) '+';
+        lookUpBase64Alphabet[63] = (byte) '/';
+    }
+
+    private static boolean isBase64(byte octect) {
+        if (octect == PAD) {
+            return true;
+        } else if (base64Alphabet[octect] == -1) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    /**
+     * Tests a given byte array to see if it contains
+     * only valid characters within the Base64 alphabet.
+     *
+     * @param arrayOctect byte array to test
+     * @return true if all bytes are valid characters in the Base64
+     *         alphabet or if the byte array is empty; false, otherwise
+     */
+    public static boolean isArrayByteBase64(byte[] arrayOctect) {
+
+        arrayOctect = discardWhitespace(arrayOctect);
+
+        int length = arrayOctect.length;
+        if (length == 0) {
+            // shouldn't a 0 length array be valid base64 data?
+            // return false;
+            return true;
+        }
+        for (int i = 0; i < length; i++) {
+            if (!isBase64(arrayOctect[i])) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Encodes binary data using the base64 algorithm but
+     * does not chunk the output.
+     *
+     * @param binaryData binary data to encode
+     * @return Base64 characters
+     */
+    public static byte[] encodeBase64(byte[] binaryData) {
+        return encodeBase64(binaryData, false);
+    }
+
+    /**
+     * Encodes binary data using the base64 algorithm and chunks
+     * the encoded output into 76 character blocks
+     *
+     * @param binaryData binary data to encode
+     * @return Base64 characters chunked in 76 character blocks
+     */
+    public static byte[] encodeBase64Chunked(byte[] binaryData) {
+        return encodeBase64(binaryData, true);
+    }
+
+    /**
+     * Decodes a byte[] containing containing
+     * characters in the Base64 alphabet.
+     *
+     * @param pArray A byte array containing Base64 character data
+     * @return a byte array containing binary data
+     */
+    public static byte[] decode(byte[] pArray) {
+        return decodeBase64(pArray);
+    }
+
+    /**
+     * Encodes binary data using the base64 algorithm, optionally
+     * chunking the output into 76 character blocks.
+     *
+     * @param binaryData Array containing binary data to encode.
+     * @param isChunked if isChunked is true this encoder will chunk
+     *                  the base64 output into 76 character blocks
+     * @return Base64-encoded data.
+     */
+    public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
+        int lengthDataBits = binaryData.length * EIGHTBIT;
+        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
+        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
+        byte encodedData[] = null;
+        int encodedDataLength = 0;
+        int nbrChunks = 0;
+
+        if (fewerThan24bits != 0) {
+            //data not divisible by 24 bit
+            encodedDataLength = (numberTriplets + 1) * 4;
+        } else {
+            // 16 or 8 bit
+            encodedDataLength = numberTriplets * 4;
+        }
+
+        // If the output is to be "chunked" into 76 character sections,
+        // for compliance with RFC 2045 MIME, then it is important to
+        // allow for extra length to account for the separator(s)
+        if (isChunked) {
+
+            nbrChunks =
+                (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
+            encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
+        }
+
+        encodedData = new byte[encodedDataLength];
+
+        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
+
+        int encodedIndex = 0;
+        int dataIndex = 0;
+        int i = 0;
+        int nextSeparatorIndex = CHUNK_SIZE;
+        int chunksSoFar = 0;
+
+        //log.debug("number of triplets = " + numberTriplets);
+        for (i = 0; i < numberTriplets; i++) {
+            dataIndex = i * 3;
+            b1 = binaryData[dataIndex];
+            b2 = binaryData[dataIndex + 1];
+            b3 = binaryData[dataIndex + 2];
+
+            //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
+
+            l = (byte) (b2 & 0x0f);
+            k = (byte) (b1 & 0x03);
+
+            byte val1 =
+                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+            byte val2 =
+                ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
+            byte val3 =
+                ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
+
+            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+            //log.debug( "val2 = " + val2 );
+            //log.debug( "k4   = " + (k<<4) );
+            //log.debug(  "vak  = " + (val2 | (k<<4)) );
+            encodedData[encodedIndex + 1] =
+                lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex + 2] =
+                lookUpBase64Alphabet[(l << 2) | val3];
+            encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
+
+            encodedIndex += 4;
+
+            // If we are chunking, let's put a chunk separator down.
+            if (isChunked) {
+                // this assumes that CHUNK_SIZE % 4 == 0
+                if (encodedIndex == nextSeparatorIndex) {
+                    System.arraycopy(
+                        CHUNK_SEPARATOR,
+                        0,
+                        encodedData,
+                        encodedIndex,
+                        CHUNK_SEPARATOR.length);
+                    chunksSoFar++;
+                    nextSeparatorIndex =
+                        (CHUNK_SIZE * (chunksSoFar + 1)) +
+                        (chunksSoFar * CHUNK_SEPARATOR.length);
+                    encodedIndex += CHUNK_SEPARATOR.length;
+                }
+            }
+        }
+
+        // form integral number of 6-bit groups
+        dataIndex = i * 3;
+
+        if (fewerThan24bits == EIGHTBIT) {
+            b1 = binaryData[dataIndex];
+            k = (byte) (b1 & 0x03);
+            //log.debug("b1=" + b1);
+            //log.debug("b1<<2 = " + (b1>>2) );
+            byte val1 =
+                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+            encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
+            encodedData[encodedIndex + 2] = PAD;
+            encodedData[encodedIndex + 3] = PAD;
+        } else if (fewerThan24bits == SIXTEENBIT) {
+
+            b1 = binaryData[dataIndex];
+            b2 = binaryData[dataIndex + 1];
+            l = (byte) (b2 & 0x0f);
+            k = (byte) (b1 & 0x03);
+
+            byte val1 =
+                ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
+            byte val2 =
+                ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
+
+            encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
+            encodedData[encodedIndex + 1] =
+                lookUpBase64Alphabet[val2 | (k << 4)];
+            encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
+            encodedData[encodedIndex + 3] = PAD;
+        }
+
+        if (isChunked) {
+            // we also add a separator to the end of the final chunk.
+            if (chunksSoFar < nbrChunks) {
+                System.arraycopy(
+                    CHUNK_SEPARATOR,
+                    0,
+                    encodedData,
+                    encodedDataLength - CHUNK_SEPARATOR.length,
+                    CHUNK_SEPARATOR.length);
+            }
+        }
+
+        return encodedData;
+    }
+
+    /**
+     * Decodes Base64 data into octects
+     *
+     * @param base64Data Byte array containing Base64 data
+     * @return Array containing decoded data.
+     */
+    public static byte[] decodeBase64(byte[] base64Data) {
+        // RFC 2045 requires that we discard ALL non-Base64 characters
+        base64Data = discardNonBase64(base64Data);
+
+        // handle the edge case, so we don't have to worry about it later
+        if (base64Data.length == 0) {
+            return new byte[0];
+        }
+
+        int numberQuadruple = base64Data.length / FOURBYTE;
+        byte decodedData[] = null;
+        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
+
+        // Throw away anything not in base64Data
+
+        int encodedIndex = 0;
+        int dataIndex = 0;
+        {
+            // this sizes the output array properly - rlw
+            int lastData = base64Data.length;
+            // ignore the '=' padding
+            while (base64Data[lastData - 1] == PAD) {
+                if (--lastData == 0) {
+                    return new byte[0];
+                }
+            }
+            decodedData = new byte[lastData - numberQuadruple];
+        }
+
+        for (int i = 0; i < numberQuadruple; i++) {
+            dataIndex = i * 4;
+            marker0 = base64Data[dataIndex + 2];
+            marker1 = base64Data[dataIndex + 3];
+
+            b1 = base64Alphabet[base64Data[dataIndex]];
+            b2 = base64Alphabet[base64Data[dataIndex + 1]];
+
+            if (marker0 != PAD && marker1 != PAD) {
+                //No PAD e.g 3cQl
+                b3 = base64Alphabet[marker0];
+                b4 = base64Alphabet[marker1];
+
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+                decodedData[encodedIndex + 1] =
+                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+                decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
+            } else if (marker0 == PAD) {
+                //Two PAD e.g. 3c[Pad][Pad]
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+            } else if (marker1 == PAD) {
+                //One PAD e.g. 3cQ[Pad]
+                b3 = base64Alphabet[marker0];
+
+                decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
+                decodedData[encodedIndex + 1] =
+                    (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
+            }
+            encodedIndex += 3;
+        }
+        return decodedData;
+    }
+
+    /**
+     * Discards any whitespace from a base-64 encoded block.
+     *
+     * @param data The base-64 encoded data to discard the whitespace
+     * from.
+     * @return The data, less whitespace (see RFC 2045).
+     */
+    static byte[] discardWhitespace(byte[] data) {
+        byte groomedData[] = new byte[data.length];
+        int bytesCopied = 0;
+
+        for (int i = 0; i < data.length; i++) {
+            switch (data[i]) {
+            case (byte) ' ' :
+            case (byte) '\n' :
+            case (byte) '\r' :
+            case (byte) '\t' :
+                    break;
+            default:
+                    groomedData[bytesCopied++] = data[i];
+            }
+        }
+
+        byte packedData[] = new byte[bytesCopied];
+
+        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
+
+        return packedData;
+    }
+
+    /**
+     * Discards any characters outside of the base64 alphabet, per
+     * the requirements on page 25 of RFC 2045 - "Any characters
+     * outside of the base64 alphabet are to be ignored in base64
+     * encoded data."
+     *
+     * @param data The base-64 encoded data to groom
+     * @return The data, less non-base64 characters (see RFC 2045).
+     */
+    static byte[] discardNonBase64(byte[] data) {
+        byte groomedData[] = new byte[data.length];
+        int bytesCopied = 0;
+
+        for (int i = 0; i < data.length; i++) {
+            if (isBase64(data[i])) {
+                groomedData[bytesCopied++] = data[i];
+            }
+        }
+
+        byte packedData[] = new byte[bytesCopied];
+
+        System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
+
+        return packedData;
+    }
+
+    /**
+     * Encodes a byte[] containing binary data, into a byte[] containing
+     * characters in the Base64 alphabet.
+     *
+     * @param pArray a byte array containing binary data
+     * @return A byte array containing only Base64 character data
+     */
+    public static byte[] encode(byte[] pArray) {
+        return encodeBase64(pArray, false);
+    }
+
+    public static String encode(String str) throws UnsupportedEncodingException
+     {
+         String baseStr = new String(encode(str.getBytes("UTF-8")));
+         String tempStr = Disguiser.disguise(str).toUpperCase();
+         String result = tempStr+baseStr;
+         return new String(encode(result.getBytes("UTF-8")));
+     }
+
+     public static String decode(String cryptoStr) throws
+       UnsupportedEncodingException {
+       if(cryptoStr.length()<40)
+         return "";
+       try
+       {
+         String tempStr = new String(decode(cryptoStr.getBytes("UTF-8")));
+         String result = tempStr.substring(40, tempStr.length());
+         return new String(decode(result.getBytes("UTF-8")));
+       }
+       catch(ArrayIndexOutOfBoundsException ex)
+       {
+         return "";
+       }
+     }
+}

+ 24 - 0
src/main/java/com/caimei365/order/utils/helipay/ConvertUtils.java

@@ -0,0 +1,24 @@
+package com.caimei365.order.utils.helipay;
+
+/**
+ * 
+ * @ClassName: ConvertUtils
+ * @Description: 格式转化工具类
+ *
+ */
+public abstract class ConvertUtils {
+
+	public static String toHex(byte input[]) {
+		if (input == null)
+			return null;
+		StringBuffer output = new StringBuffer(input.length * 2);
+		for (int i = 0; i < input.length; i++) {
+			int current = input[i] & 0xff;
+			if (current < 16)
+				output.append("0");
+			output.append(Integer.toString(current, 16));
+		}
+
+		return output.toString();
+	}
+}

+ 63 - 0
src/main/java/com/caimei365/order/utils/helipay/DesUtils.java

@@ -0,0 +1,63 @@
+package com.caimei365.order.utils.helipay;
+
+import javax.crypto.*;
+import javax.crypto.spec.SecretKeySpec;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+public class DesUtils {
+
+    public static final String ENCODE = "UTF-8";
+
+    private DesUtils() {
+    }
+
+    public static String encode(String key, String data) throws NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
+        try {
+            byte[] keyByte = key.getBytes(ENCODE);
+            byte[] dataByte = data.getBytes(ENCODE);
+            byte[] valueByte = des3Encryption(
+                    keyByte, dataByte);
+            String value = new String(Base64.encodeBase64(valueByte), ENCODE);
+            return value;
+        } catch (Exception e) {
+            System.err.println("3des加密失败:" + e.getMessage());
+            throw e;
+        }
+    }
+
+    public static String decode(String key, String value) throws NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
+        try {
+            byte[] keyByte = key.getBytes(ENCODE);
+            byte[] bytes = value.getBytes(ENCODE);
+            byte[] dataByte = des3Decryption(keyByte,
+                    Base64.decode(bytes));
+            String data = new String(dataByte, ENCODE);
+            return data;
+        } catch (Exception e) {
+            System.err.println("3des解密失败:" + e.getMessage());
+            throw e;
+        }
+    }
+
+    private static byte[] des3Encryption(byte[] key, byte[] data) throws
+            NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
+            BadPaddingException, IllegalBlockSizeException, IllegalStateException {
+        final String Algorithm = "DESede";
+        SecretKey deskey = new SecretKeySpec(key, Algorithm);
+        Cipher c1 = Cipher.getInstance(Algorithm);
+        c1.init(Cipher.ENCRYPT_MODE, deskey);
+        return c1.doFinal(data);
+    }
+
+    private static byte[] des3Decryption(byte[] key, byte[] data) throws
+            NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
+            BadPaddingException, IllegalBlockSizeException, IllegalStateException {
+        final String Algorithm = "DESede";
+        SecretKey deskey = new SecretKeySpec(key, Algorithm);
+        Cipher c1 = Cipher.getInstance(Algorithm);
+        c1.init(Cipher.DECRYPT_MODE, deskey);
+        return c1.doFinal(data);
+    }
+}

+ 74 - 0
src/main/java/com/caimei365/order/utils/helipay/Disguiser.java

@@ -0,0 +1,74 @@
+package com.caimei365.order.utils.helipay;
+
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+
+/**
+ * 
+ * @ClassName: Disguiser
+ * @Description: 哈希算法的工具类,提供SHA MD5 HMAC等算法
+ *
+ */
+public class Disguiser {
+
+	public static final String ENCODE = "UTF-8";
+	private static final String KEY = "8data998mnwepxugnk03-2zirb";
+
+	public static String disguiseMD5(String message) {
+
+		if (null == message) {
+			return null;
+		}
+		return disguiseMD5(message, ENCODE);
+	}
+	
+	public static String disguise(String message){
+    	return disguise(message+KEY,ENCODE);
+    	
+    }
+	public static String disguise(String message,String encoding){
+    	message = message.trim();
+        byte value[];
+        try{
+            value = message.getBytes(encoding);
+        }
+        catch(UnsupportedEncodingException e){
+            value = message.getBytes();
+        }
+        MessageDigest md = null;
+        try{
+            md = MessageDigest.getInstance("SHA");
+        }catch(NoSuchAlgorithmException e){
+        	e.printStackTrace();
+            return null;
+        }
+        return ConvertUtils.toHex(md.digest(value));
+    }
+
+	public static String disguiseMD5(String message, String encoding) {
+
+		if (null == message || null == encoding) {
+
+			return null;
+		}
+
+		message = message.trim();
+		byte value[];
+		try {
+			value = message.getBytes(encoding);
+		} catch (UnsupportedEncodingException e) {
+			value = message.getBytes();
+		}
+		MessageDigest md = null;
+		try {
+			md = MessageDigest.getInstance("MD5");
+		} catch (NoSuchAlgorithmException e) {
+			e.printStackTrace();
+			return null;
+		}
+		return ConvertUtils.toHex(md.digest(value));
+	}
+
+}

+ 127 - 0
src/main/java/com/caimei365/order/utils/helipay/HttpClientService.java

@@ -0,0 +1,127 @@
+package com.caimei365.order.utils.helipay;
+
+import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.params.HttpMethodParams;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.*;
+
+public class HttpClientService {
+
+    private static final Log LOG = LogFactory.getLog(HttpClientService.class);
+
+    public static Map<String, Object> getHttpResp(Map<String, String> reqMap, String httpUrl) {
+        HttpClient client = new HttpClient();
+        PostMethod method = new PostMethod(httpUrl);
+        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
+        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
+        method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(300000));
+        String response = "";
+
+
+        Map<String, Object> mp = new HashMap<String, Object>();
+
+        try {
+            NameValuePair[] nvps = getNameValuePair(reqMap);
+            method.setRequestBody(nvps);
+            int rescode = client.executeMethod(method);
+            mp.put("statusCode", rescode);
+
+            LOG.info("http rescode:" + rescode);
+            if (rescode == HttpStatus.SC_OK) {
+                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
+                String curline = "";
+                while ((curline = reader.readLine()) != null) {
+                    response += curline;
+                }
+                LOG.info("http response:" + response);
+                mp.put("response", response);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            method.releaseConnection();
+        }
+        return mp;
+    }
+
+    /**
+     *
+     * HTTP协议POST请求方法
+     */
+    public static String httpMethodPost(String url, String params, String gb) {
+        if (null == gb || "".equals(gb)) {
+            gb = "UTF-8";
+        }
+        StringBuffer sb = new StringBuffer();
+        URL urls;
+        HttpURLConnection uc = null;
+        BufferedReader in = null;
+        DataOutputStream out = null;
+        try {
+            urls = new URL(url);
+            uc = (HttpURLConnection) urls.openConnection();
+            uc.setRequestMethod("POST");
+            uc.setDoOutput(true);
+            uc.setDoInput(true);
+            uc.setUseCaches(false);
+            uc.setRequestProperty("Connection", "keep-alive");
+            uc.setRequestProperty("Keep-Alive", "timeout=1, max=100");
+            uc.setRequestProperty("Content-Length", params.length() + "");
+            uc.setRequestProperty("Content-Type","application/json");
+            uc.setConnectTimeout(7000);
+            uc.setReadTimeout(10000);
+            uc.connect();
+            out = new DataOutputStream(uc.getOutputStream());
+            out.write(params.getBytes(gb));
+            out.flush();
+            out.close();
+            in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
+                    gb));
+            String readLine = "";
+            while ((readLine = in.readLine()) != null) {
+                sb.append(readLine);
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (out != null){
+                    out.close();
+                }
+                if (in != null){
+                    in.close();
+                }
+                if (uc != null) {
+                    uc.disconnect();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return sb.toString();
+    }
+
+    public static NameValuePair[] getNameValuePair(Map<String, String> bean) {
+        List<NameValuePair> x = new ArrayList<NameValuePair>();
+        for (Iterator<String> iterator = bean.keySet().iterator(); iterator.hasNext(); ) {
+            String type = (String) iterator.next();
+            x.add(new NameValuePair(type, String.valueOf(bean.get(type))));
+        }
+        Object[] y = x.toArray();
+        NameValuePair[] n = new NameValuePair[y.length];
+        System.arraycopy(y, 0, n, 0, y.length);
+        return n;
+    }
+}

+ 113 - 0
src/main/java/com/caimei365/order/utils/helipay/MyBeanUtils.java

@@ -0,0 +1,113 @@
+package com.caimei365.order.utils.helipay;
+
+
+import com.caimei365.order.constant.Constant;
+import org.apache.commons.beanutils.BeanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.beans.IntrospectionException;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ *
+ */
+public class MyBeanUtils extends BeanUtils{
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(MyBeanUtils.class);
+
+    private MyBeanUtils(){ }
+
+    public static Map convertBean(Object bean, Map retMap)
+            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
+        Class clazz = bean.getClass();
+        Field[] fields = clazz.getDeclaredFields();
+        for (Field f : fields) {
+            f.setAccessible(true);
+        }
+        for (Field f : fields) {
+            String key = f.toString().substring(f.toString().lastIndexOf(".") + 1);
+            if (StringUtils.equalsIgnoreCase("NEED_SIGN_PARAMS", key)) {
+                continue;
+            }
+            Object value = f.get(bean);
+            if (value == null)
+                value = "";
+            retMap.put(key, value);
+        }
+        return retMap;
+    }
+
+    public static String getSigned(Map<String, String> map, String[] excludes){
+        StringBuffer sb = new StringBuffer();
+        Set<String> excludeSet = new HashSet<String>();
+        excludeSet.add("sign");
+        if(excludes != null){
+            for(String exclude : excludes){
+                excludeSet.add(exclude);
+            }
+        }
+        for(String key : map.keySet()){
+            if(!excludeSet.contains(key)){
+                String value = map.get(key);
+                value = (value == null ? "" : value);
+                sb.append(Constant.SPLIT);
+                sb.append(value);
+            }
+        }
+//        sb.append(Constant.SPLIT);
+        return sb.toString();
+    }
+
+    public static String getSigned(Object bean, String[] excludes) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
+        Map map  = convertBean(bean, new LinkedHashMap());
+        String signedStr = getSigned(map, excludes);
+        return signedStr;
+    }
+
+    /**
+     * new style
+     *
+     * @param bean
+     * @param needSignParams
+     */
+    public static String getSignedByPresetParameter(Object bean, Set<String> needSignParams) throws IllegalAccessException,
+            IntrospectionException, InvocationTargetException {
+        Map map = convertBean(bean, new LinkedHashMap<>());
+        return getSignedByPresetParameter(map, needSignParams);
+    }
+
+    /**
+     * new style
+     *
+     * @param map
+     * @param needSignParams
+     * @return
+     */
+    public static String getSignedByPresetParameter(Map<String, String> map, Set<String> needSignParams) {
+        StringBuffer sb = new StringBuffer();
+        if (needSignParams == null || needSignParams.isEmpty()) {
+            throw new RuntimeException("needSignParams is required");
+        }
+        for (String key : map.keySet()) {
+            if (needSignParams.contains(key)) {
+                // do sign
+                String value = map.get(key);
+                value = (value == null ? "" : value);
+                sb.append(Constant.SPLIT);
+                sb.append(value);
+            }
+        }
+//        改为手动拼接密钥
+//        sb.append(Constant.SPLIT).append(Constant.SAOMA);
+        //LOGGER.info("sign result:{}", sb.toString());
+        return sb.toString();
+    }
+
+}

+ 25 - 0
src/main/java/com/caimei365/order/utils/helipay/MyDateUtils.java

@@ -0,0 +1,25 @@
+package com.caimei365.order.utils.helipay;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * @author awu
+ */
+public class MyDateUtils {
+
+    private MyDateUtils(){
+
+    }
+
+    public static SimpleDateFormat format (){
+        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
+        return format;
+    }
+
+    public static String getDate2Str(Date date) {
+        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
+        return format.format(date);
+    }
+
+}

+ 350 - 0
src/main/java/com/caimei365/order/utils/helipay/RSA.java

@@ -0,0 +1,350 @@
+package com.caimei365.order.utils.helipay;
+
+import org.apache.commons.lang.ArrayUtils;
+import sun.misc.BASE64Encoder;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.security.*;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateFactory;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Arrays;
+import java.util.Enumeration;
+
+/**
+ * 私钥签名,私钥签名(只有私钥能签),公钥验证签名,确认发起人是私钥持有人
+ * 公钥加密,公钥加密只有私钥能解密
+ *
+ * @author datou
+ */
+public class RSA {
+
+    /**
+     * String to hold name of the encryption padding.
+     */
+    public static final String NOPADDING = "RSA/NONE/NoPadding";
+
+    public static final String RSANONEPKCS1PADDING = "RSA/NONE/PKCS1Padding";
+
+    public static final String RSAECBPKCS1PADDING = "RSA/ECB/PKCS1Padding";
+
+    public static final String PROVIDER = "BC";
+
+    static {
+        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
+    }
+
+    /**
+     * 验证签名
+     *
+     * @param data     数据
+     * @param sign     签名
+     * @param publicKey 公钥
+     * @return
+     */
+    public static boolean verifySign(byte[] data, byte[] sign,
+                                     PublicKey publicKey) {
+        try {
+            Signature signature = Signature
+                    .getInstance("MD5withRSA");
+            signature.initVerify(publicKey);
+            signature.update(data);
+            boolean result = signature.verify(sign);
+            return result;
+        } catch (Exception e) {
+
+            throw new RuntimeException("verifySign fail!", e);
+        }
+    }
+
+    /**
+     * 验证签名
+     *
+     * @param data     数据
+     * @param sign     签名
+     * @param pubicKey 公钥
+     * @return
+     */
+    public static boolean verifySign(String data, String sign,
+                                     PublicKey pubicKey) {
+        try {
+            byte[] dataByte = data
+                    .getBytes("UTF-8");
+            byte[] signByte = Base64.decode(sign
+                    .getBytes("UTF-8"));
+            return verifySign(dataByte, signByte, pubicKey);
+        } catch (UnsupportedEncodingException e) {
+
+            throw new RuntimeException("verifySign fail! data[" + data + "] sign[" + sign + "]", e);
+        }
+    }
+
+    /**
+     * 签名
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static byte[] sign(byte[] data, PrivateKey key) {
+        try {
+            Signature signature = Signature
+                    .getInstance("MD5withRSA");
+            signature.initSign(key);
+            signature.update(data);
+            return signature.sign();
+        } catch (Exception e) {
+            throw new RuntimeException("sign fail!", e);
+        }
+    }
+
+    /**
+     * 签名
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static String sign(String data, PrivateKey key) {
+        try {
+            byte[] dataByte = data.getBytes("UTF-8");
+            return new String(Base64.encode(sign(dataByte, key)));
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException("sign fail!", e);
+        }
+    }
+
+    /**
+     * 加密
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static byte[] encrypt(byte[] data, Key key, String padding) {
+        try {
+            final Cipher cipher = Cipher.getInstance(padding, PROVIDER);
+            cipher.init(Cipher.ENCRYPT_MODE, key);
+            return cipher.doFinal(data);
+        } catch (Exception e) {
+
+            throw new RuntimeException("encrypt fail!", e);
+        }
+    }
+
+    /**
+     * 加密
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static String encryptToBase64(String data, Key key, String padding) {
+        try {
+            return new String(Base64.encode(encrypt(
+                    data.getBytes("UTF-8"),
+                    key, padding)));
+        } catch (Exception e) {
+            throw new RuntimeException("encrypt fail!", e);
+        }
+    }
+
+    /**
+     * 解密
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static byte[] decrypt(byte[] data, Key key, String padding) {
+        try {
+            final Cipher cipher = Cipher.getInstance(padding, PROVIDER);
+            cipher.init(Cipher.DECRYPT_MODE, key);
+            return cipher.doFinal(data);
+        } catch (Exception e) {
+            throw new RuntimeException("encrypt fail!", e);
+        }
+    }
+
+    /**
+     * 解密
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static String decryptFromBase64(String data, Key key, String padding) {
+        try {
+            return new String(decrypt(Base64.decode(data.getBytes()), key, padding),
+                    "UTF-8");
+        } catch (Exception e) {
+            throw new RuntimeException("encrypt fail!", e);
+        }
+    }
+
+    public static void createKeyPairs(int size) throws Exception {
+        // create the keys
+        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", PROVIDER);
+        generator.initialize(size, new SecureRandom());
+        KeyPair pair = generator.generateKeyPair();
+        PublicKey pubKey = pair.getPublic();
+        PrivateKey privKey = pair.getPrivate();
+        byte[] pk = pubKey.getEncoded();
+        byte[] privk = privKey.getEncoded();
+        String strpk = new String(Base64.encodeBase64(pk));
+        String strprivk = new String(Base64.encodeBase64(privk));
+        System.out.println("公钥:" + Arrays.toString(pk));
+        System.out.println("私钥:" + Arrays.toString(privk));
+        System.out.println("公钥Base64编码:" + strpk);
+        System.out.println("私钥Base64编码:" + strprivk);
+    }
+
+    public static PublicKey getPublicKey(String base64EncodePublicKey) throws Exception {
+        KeyFactory keyf = KeyFactory.getInstance("RSA", PROVIDER);
+        X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decodeBase64(base64EncodePublicKey.getBytes()));
+        PublicKey pubkey = keyf.generatePublic(pubX509);
+        return pubkey;
+    }
+
+    public static PrivateKey getPrivateKey(String base64EncodePrivateKey) throws Exception {
+        KeyFactory keyf = KeyFactory.getInstance("RSA", PROVIDER);
+        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodePrivateKey.getBytes()));
+        PrivateKey privkey = keyf.generatePrivate(priPKCS8);
+        return privkey;
+    }
+
+
+    public static byte[] encode(String encodeString, Key key, String padding) throws Exception {
+        final Cipher cipher = Cipher.getInstance(padding, PROVIDER);
+        cipher.init(Cipher.ENCRYPT_MODE, key);
+        byte[] bytes = encodeString.getBytes("UTF-8");
+        byte[] encodedByteArray = new byte[]{};
+        for (int i = 0; i < bytes.length; i += 117) {
+            byte[] subarray = ArrayUtils.subarray(bytes, i, i + 117);
+            byte[] doFinal = cipher.doFinal(subarray);
+            encodedByteArray = ArrayUtils.addAll(encodedByteArray, doFinal);
+        }
+        return encodedByteArray;
+    }
+
+    /**
+     * 加密
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static String encodeToBase64(String data, Key key, String padding) {
+        try {
+            return new String(Base64.encode(encode(data,
+                    key, padding)));
+        } catch (Exception e) {
+            throw new RuntimeException("encrypt fail!", e);
+        }
+    }
+
+    public static String decode(byte[] decodeByteArray, Key key, String padding) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException, NoSuchProviderException {
+        final Cipher cipher = Cipher.getInstance(padding, PROVIDER);
+        cipher.init(Cipher.DECRYPT_MODE, key);
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < decodeByteArray.length; i += 128) {
+            byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(decodeByteArray, i, i + 128));
+            sb.append(new String(doFinal));
+        }
+        return sb.toString();
+    }
+
+    /**
+     * 解密
+     *
+     * @param data
+     * @param key
+     * @return
+     */
+    public static String decodeFromBase64(String data, Key key, String padding) {
+        try {
+            return new String(decode(Base64.decode(data.getBytes()), key, padding).getBytes(),
+                    "UTF-8");
+        } catch (Exception e) {
+            throw new RuntimeException("encrypt fail!", e);
+        }
+    }
+
+    /**
+     * 得到密钥字符串(经过base64编码)
+     *
+     * @return
+     */
+    public static String getKeyString(Key key) throws Exception {
+        byte[] keyBytes = key.getEncoded();
+        String s = (new BASE64Encoder()).encode(keyBytes);
+        return s;
+    }
+
+    public static String getKeyStringByCer(String path) throws Exception {
+        CertificateFactory cff = CertificateFactory.getInstance("X.509");
+        FileInputStream fis1 = new FileInputStream(path);
+        Certificate cf = cff.generateCertificate(fis1);
+        PublicKey pk1 = cf.getPublicKey();
+        String key = getKeyString(pk1);
+        System.out.println("public:\n" + key);
+        return key;
+    }
+
+    public static String getKeyStringByPfx(String strPfx, String strPassword) {
+        try {
+            KeyStore ks = KeyStore.getInstance("PKCS12");
+            FileInputStream fis = new FileInputStream(strPfx);
+            // If the keystore password is empty(""), then we have to set
+            // to null, otherwise it won't work!!!
+            char[] nPassword = null;
+            if ((strPassword == null) || strPassword.trim().equals("")) {
+                nPassword = null;
+            } else {
+                nPassword = strPassword.toCharArray();
+            }
+            ks.load(fis, nPassword);
+            fis.close();
+            System.out.println("keystore type=" + ks.getType());
+            // Now we loop all the aliases, we need the alias to get keys.
+            // It seems that this value is the "Friendly name" field in the
+            // detals tab <-- Certificate window <-- view <-- Certificate
+            // Button <-- Content tab <-- Internet Options <-- Tools menu
+            // In MS IE 6.
+            Enumeration enumas = ks.aliases();
+            String keyAlias = null;
+            if (enumas.hasMoreElements())// we are readin just one certificate.
+            {
+                keyAlias = (String) enumas.nextElement();
+                System.out.println("alias=[" + keyAlias + "]");
+            }
+            // Now once we know the alias, we could get the keys.
+            System.out.println("is key entry=" + ks.isKeyEntry(keyAlias));
+            PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
+            Certificate cert = ks.getCertificate(keyAlias);
+            PublicKey pubkey = cert.getPublicKey();
+
+            String basePrikey = RSA.getKeyString(prikey);
+            System.out.println("cert class = " + cert.getClass().getName());
+            System.out.println("cert = " + cert);
+            System.out.println("public key = " + pubkey);
+            System.out.println("private key = " + prikey);
+            System.out.println("pubkey key = " + RSA.getKeyString(pubkey));
+            System.out.println("prikey key = " + RSA.getKeyString(prikey));
+            System.out.println("pubkey key length = " + RSA.getKeyString(pubkey).length());
+            System.out.println("prikey key length = " + RSA.getKeyString(prikey).length());
+            return basePrikey;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+}