(微信支付)企業(yè)付款到銀行卡

微信官方文檔

https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_2

調(diào)用獲取RSA公鑰API

https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_7

1.獲取PKCS#1格式的公鑰

public static void getPublicKey() throws Exception {

? ? ? ? String nonce_str= MD5Utils.getMessageDigest(String.valueOf(new Random().nextInt(10000)).getBytes());//隨機數(shù)

? ? ? ? //簽名數(shù)據(jù)

? ? ? ? Map<String, String> packageParams = new HashMap<>();

? ? ? ? packageParams.put("mch_id", MERID);//微信支付分配的商戶號

? ? ? ? packageParams.put("nonce_str",nonce_str);//隨機字符串碉钠,不長于32位棉钧。推薦隨機數(shù)生成算法

? ? ? ? packageParams.put("sign_type", "MD5");//簽名類型的圆,目前支持HMAC-SHA256和MD5祈争,默認為MD5

? ? ? ? // 把數(shù)組所有元素,按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串

? ? ? ? String prestr = PayUtil.createLinkString(packageParams);

? ? ? ? //MD5運算生成簽名,這里是第一次簽名,用于調(diào)用統(tǒng)一下單接口

? ? ? ? String sign = PayUtil.sign(prestr, SIGNKEY, "utf-8").toUpperCase();

? ? ? ? //封裝xml報文

? ? ? ? String xml="<xml>"+

? ? ? ? ? ? ? ? "<mch_id>"+MERID+"</mch_id>"+

? ? ? ? ? ? ? ? "<nonce_str>"+nonce_str+"</nonce_str>"+

? ? ? ? ? ? ? ? "<sign>"+sign+"</sign>"+

? ? ? ? ? ? ? ? "<sign_type>"+"MD5"+"</sign_type>"+

? ? ? ? ? ? ? ? "</xml>";

? ? ? ? String createOrderURL = "https://fraud.mch.weixin.qq.com/risk/getpublickey";//獲取RSA加密公鑰API

? ? ? ? //調(diào)用統(tǒng)一下單接口,并接受返回的結(jié)果

? ? ? ? System.out.println(xml);

? ? ? ? String post = ClientCustomSSL.paybank(createOrderURL, xml);

? ? ? ? System.out.println(post);

? ? ? ? String postString = XML.toJSONObject(post).toString();

? ? ? ? String wxinfo = postString.substring(postString.indexOf(":") + 1, postString.length() - 1);

? ? ? ? System.out.println(wxinfo);

}

2.返回示例

<xml>

<return_code>SUCCESS</return_code>

<return_msg>OK</return_msg>

<result_code>SUCCESS</result_code>

<mch_id>XXXXXXXX</mch_id>

<pub_key>

-----BEGIN?RSA?PUBLIC?KEY-----

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

-----END?RSA?PUBLIC?KEY-----

</pub_key>

</xml>

3.轉(zhuǎn)換PKCS公鑰格式

filename :為public.pem地址

PKCS#1 轉(zhuǎn) PKCS#8:

openssl rsa -RSAPublicKey_in -in <filename> -pubout

PKCS#8 轉(zhuǎn) PKCS#1:

openssl rsa -pubin -in <filename> -RSAPublicKey_out

需要安裝openSSL,配置環(huán)境變量 需要區(qū)分系統(tǒng)

4.將得到的PKCS#8公鑰轉(zhuǎn)換為base64

public static String getRsa() throws Exception {

? ? String encBankAcctNo = "JOKER"; //加密的銀行賬號仪或、或者名稱

? ? String keyfile = "C:\\Users\\o\\Desktop\\WXCertUtil\\cert\\XXXXXXXXXX_cert\\pksc8_public.pem"; //讀取PKCS8密鑰文件

? ? PublicKey pub=RSAUtil.getPubKey(keyfile,"RSA");

? ? //用標準的RSA加密庫對敏感信息進行加密,選擇RSA_PKCS1_OAEP_PADDING填充模式(eg:Java的填充方式要選 " RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING")

? ? String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";

? ? byte[] estr=RSAUtil.encrypt(encBankAcctNo.getBytes(),pub,2048, 11,rsa);? //對銀行賬號進行加密

? encBankAcctNo =Base64.encode(estr);//并轉(zhuǎn)為base64格式

? ? return encBankAcctNo;

}

5.調(diào)用https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank 接口實現(xiàn)微信支付到銀行卡

@PostMapping("/paybankcard")

@ApiOperation("微信賬戶付款到銀行卡")

public Result<String> payBankCard() throws Exception {

? ? String nonce_str= MD5Utils.getMessageDigest(String.valueOf(new Random().nextInt(10000)).getBytes());//隨機數(shù)

? ? int randomNum? = (int) (Math.random() * 1999+5000);

? ? //"商戶企業(yè)付款單號";

? ? String partner_trade_no = TimeUtils.getSysTime("yyyyMMddHHmmss") + randomNum;//生成訂單號

? ? String enc_bank_no = "XXXXXXXXX";

? ? String enc_true_name = "XXXXXXXXXX";

? ? String bank_code = "1005";

? ? int amount = 100;

? ? String desc = "測試到賬";

? ? //簽名數(shù)據(jù)

? ? Map<String, String> packageParams = new HashMap<>();

? ? packageParams.put("mch_id",MERID);

? ? packageParams.put("partner_trade_no",partner_trade_no);

? ? packageParams.put("nonce_str",nonce_str);

? ? packageParams.put("enc_bank_no",enc_bank_no);

? ? packageParams.put("enc_true_name",enc_true_name);

? ? packageParams.put("bank_code", bank_code);

? ? packageParams.put("amount",String.valueOf(amount));

? ? packageParams.put("desc", desc);

? ? // 把數(shù)組所有元素士骤,按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串

? ? String prestr = PayUtil.createLinkString(packageParams);

? ? //MD5運算生成簽名范删,這里是第一次簽名,用于調(diào)用統(tǒng)一下單接口

? ? String sign = PayUtil.sign(prestr, SIGNKEY, "utf-8").toUpperCase();

? ? LOGGER.info("sign="+sign);

? ? //封裝xml報文

? ? String xml="<xml>"+

? ? ? ? ? ? "<amount>"+amount+"</amount>"+

? ? ? ? ? ? "<bank_code>"+bank_code+"</bank_code>"+

? ? ? ? ? ? "<desc>"+desc+"</desc>"+

? ? ? ? ? ? "<enc_bank_no>"+enc_bank_no+"</enc_bank_no>"+

? ? ? ? ? ? "<enc_true_name>"+enc_true_name+"</enc_true_name>"+

? ? ? ? ? ? "<mch_id>"+ MERID+"</mch_id>"+

? ? ? ? ? ? "<nonce_str>"+nonce_str+"</nonce_str>"+

? ? ? ? ? ? "<partner_trade_no>"+ partner_trade_no+"</partner_trade_no>"+

? ? ? ? ? ? "<sign>"+sign+"</sign>"+

? ? ? ? ? ? "</xml>";

? ? String createOrderURL = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";//微信統(tǒng)一下單接口

? ? //調(diào)用統(tǒng)一下單接口拷肌,并接受返回的結(jié)果

? ? System.out.println(xml);

? ? String post = ClientCustomSSL.doRefund(createOrderURL,xml);

? ? String postString = XML.toJSONObject(post).toString();

? ? String wxinfo = postString.substring(postString.indexOf(":") + 1, postString.length() - 1);

? ? System.out.println(wxinfo);

? ? return Result.success();

}

6.工具類

package com.qiouou.common.util.wxH5Pay;

/**

* @program: guidePlus

* @description

* @author: Joker

* @create: 2021-04-15 11:50

**/

public class Base64 {

? ? static private final int? ? BASELENGTH? ? ? ? ? = 128;

? ? static private final int? ? LOOKUPLENGTH? ? ? ? = 64;

? ? static private final int? ? TWENTYFOURBITGROUP? = 24;

? ? static private final int? ? EIGHTBIT? ? ? ? ? ? = 8;

? ? static private final int? ? SIXTEENBIT? ? ? ? ? = 16;

? ? static private final int? ? FOURBYTE? ? ? ? ? ? = 4;

? ? static private final int? ? SIGN? ? ? ? ? ? ? ? = -128;

? ? static private final char? ? PAD? ? ? ? ? ? ? ? ? = '=';

? ? static private final boolean fDebug? ? ? ? ? ? ? = false;

? ? static final private byte[]? base64Alphabet? ? ? = new byte[BASELENGTH];

? ? static final private char[]? lookUpBase64Alphabet = new char[LOOKUPLENGTH];

? ? static {

? ? ? ? for (int i = 0; i < BASELENGTH; ++i) {

? ? ? ? ? ? base64Alphabet[i] = -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] = (char) ('A' + i);

? ? ? ? }

? ? ? ? for (int i = 26, j = 0; i <= 51; i++, j++) {

? ? ? ? ? ? lookUpBase64Alphabet[i] = (char) ('a' + j);

? ? ? ? }

? ? ? ? for (int i = 52, j = 0; i <= 61; i++, j++) {

? ? ? ? ? ? lookUpBase64Alphabet[i] = (char) ('0' + j);

? ? ? ? }

? ? ? ? lookUpBase64Alphabet[62] = (char) '+';

? ? ? ? lookUpBase64Alphabet[63] = (char) '/';

? ? }

? ? private static boolean isWhiteSpace(char octect) {

? ? ? ? return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);

? ? }

? ? private static boolean isPad(char octect) {

? ? ? ? return (octect == PAD);

? ? }

? ? private static boolean isData(char octect) {

? ? ? ? return (octect < BASELENGTH && base64Alphabet[octect] != -1);

? ? }

? ? /**

? ? * Encodes hex octects into Base64

? ? *

? ? * @param binaryData Array containing binaryData

? ? * @return Encoded Base64 array

? ? */

? ? public static String encode(byte[] binaryData) {

? ? ? ? if (binaryData == null) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? int lengthDataBits = binaryData.length * EIGHTBIT;

? ? ? ? if (lengthDataBits == 0) {

? ? ? ? ? ? return "";

? ? ? ? }

? ? ? ? int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;

? ? ? ? int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;

? ? ? ? int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;

? ? ? ? char encodedData[] = null;

? ? ? ? encodedData = new char[numberQuartet * 4];

? ? ? ? byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

? ? ? ? int encodedIndex = 0;

? ? ? ? int dataIndex = 0;

? ? ? ? if (fDebug) {

? ? ? ? ? ? System.out.println("number of triplets = " + numberTriplets);

? ? ? ? }

? ? ? ? for (int i = 0; i < numberTriplets; i++) {

? ? ? ? ? ? b1 = binaryData[dataIndex++];

? ? ? ? ? ? b2 = binaryData[dataIndex++];

? ? ? ? ? ? b3 = binaryData[dataIndex++];

? ? ? ? ? ? if (fDebug) {

? ? ? ? ? ? ? ? System.out.println("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);

? ? ? ? ? ? if (fDebug) {

? ? ? ? ? ? ? ? System.out.println("val2 = " + val2);

? ? ? ? ? ? ? ? System.out.println("k4? = " + (k << 4));

? ? ? ? ? ? ? ? System.out.println("vak? = " + (val2 | (k << 4)));

? ? ? ? ? ? }

? ? ? ? ? ? encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];

? ? ? ? ? ? encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];

? ? ? ? ? ? encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];

? ? ? ? ? ? encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];

? ? ? ? }

? ? ? ? // form integral number of 6-bit groups

? ? ? ? if (fewerThan24bits == EIGHTBIT) {

? ? ? ? ? ? b1 = binaryData[dataIndex];

? ? ? ? ? ? k = (byte) (b1 & 0x03);

? ? ? ? ? ? if (fDebug) {

? ? ? ? ? ? ? ? System.out.println("b1=" + b1);

? ? ? ? ? ? ? ? System.out.println("b1<<2 = " + (b1 >> 2));

? ? ? ? ? ? }

? ? ? ? ? ? byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);

? ? ? ? ? ? encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];

? ? ? ? ? ? encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];

? ? ? ? ? ? encodedData[encodedIndex++] = PAD;

? ? ? ? ? ? encodedData[encodedIndex++] = 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++] = lookUpBase64Alphabet[val2 | (k << 4)];

? ? ? ? ? ? encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];

? ? ? ? ? ? encodedData[encodedIndex++] = PAD;

? ? ? ? }

? ? ? ? return new String(encodedData);

? ? }

? ? /**

? ? * Decodes Base64 data into octects

? ? *

? ? * @param encoded string containing Base64 data

? ? * @return Array containind decoded data.

? ? */

? ? public static byte[] decode(String encoded) {

? ? ? ? if (encoded == null) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? char[] base64Data = encoded.toCharArray();

? ? ? ? // remove white spaces

? ? ? ? int len = removeWhiteSpace(base64Data);

? ? ? ? if (len % FOURBYTE != 0) {

? ? ? ? ? ? return null;//should be divisible by four

? ? ? ? }

? ? ? ? int numberQuadruple = (len / FOURBYTE);

? ? ? ? if (numberQuadruple == 0) {

? ? ? ? ? ? return new byte[0];

? ? ? ? }

? ? ? ? byte decodedData[] = null;

? ? ? ? byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;

? ? ? ? char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

? ? ? ? int i = 0;

? ? ? ? int encodedIndex = 0;

? ? ? ? int dataIndex = 0;

? ? ? ? decodedData = new byte[(numberQuadruple) * 3];

? ? ? ? for (; i < numberQuadruple - 1; i++) {

? ? ? ? ? ? if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))

? ? ? ? ? ? ? ? ? ? || !isData((d3 = base64Data[dataIndex++]))

? ? ? ? ? ? ? ? ? ? || !isData((d4 = base64Data[dataIndex++]))) {

? ? ? ? ? ? ? ? return null;

? ? ? ? ? ? }//if found "no data" just return null

? ? ? ? ? ? b1 = base64Alphabet[d1];

? ? ? ? ? ? b2 = base64Alphabet[d2];

? ? ? ? ? ? b3 = base64Alphabet[d3];

? ? ? ? ? ? b4 = base64Alphabet[d4];

? ? ? ? ? ? decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);

? ? ? ? ? ? decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));

? ? ? ? ? ? decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

? ? ? ? }

? ? ? ? if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {

? ? ? ? ? ? return null;//if found "no data" just return null

? ? ? ? }

? ? ? ? b1 = base64Alphabet[d1];

? ? ? ? b2 = base64Alphabet[d2];

? ? ? ? d3 = base64Data[dataIndex++];

? ? ? ? d4 = base64Data[dataIndex++];

? ? ? ? if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters

? ? ? ? ? ? if (isPad(d3) && isPad(d4)) {

? ? ? ? ? ? ? ? if ((b2 & 0xf) != 0)//last 4 bits should be zero

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? return null;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? byte[] tmp = new byte[i * 3 + 1];

? ? ? ? ? ? ? ? System.arraycopy(decodedData, 0, tmp, 0, i * 3);

? ? ? ? ? ? ? ? tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);

? ? ? ? ? ? ? ? return tmp;

? ? ? ? ? ? } else if (!isPad(d3) && isPad(d4)) {

? ? ? ? ? ? ? ? b3 = base64Alphabet[d3];

? ? ? ? ? ? ? ? if ((b3 & 0x3) != 0)//last 2 bits should be zero

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? return null;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? byte[] tmp = new byte[i * 3 + 2];

? ? ? ? ? ? ? ? System.arraycopy(decodedData, 0, tmp, 0, i * 3);

? ? ? ? ? ? ? ? tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);

? ? ? ? ? ? ? ? tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));

? ? ? ? ? ? ? ? return tmp;

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? return null;

? ? ? ? ? ? }

? ? ? ? } else { //No PAD e.g 3cQl

? ? ? ? ? ? b3 = base64Alphabet[d3];

? ? ? ? ? ? b4 = base64Alphabet[d4];

? ? ? ? ? ? decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);

? ? ? ? ? ? decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));

? ? ? ? ? ? decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

? ? ? ? }

? ? ? ? return decodedData;

? ? }

? ? /**

? ? * remove WhiteSpace from MIME containing encoded Base64 data.

? ? *

? ? * @param data? the byte array of base64 data (with WS)

? ? * @return? ? ? the new length

? ? */

? ? private static int removeWhiteSpace(char[] data) {

? ? ? ? if (data == null) {

? ? ? ? ? ? return 0;

? ? ? ? }

? ? ? ? // count characters that's not whitespace

? ? ? ? int newSize = 0;

? ? ? ? int len = data.length;

? ? ? ? for (int i = 0; i < len; i++) {

? ? ? ? ? ? if (!isWhiteSpace(data[i])) {

? ? ? ? ? ? ? ? data[newSize++] = data[i];

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return newSize;

? ? }

}

package com.qiouou.common.util.wxH5Pay;

import javax.crypto.Cipher;

import java.io.*;

import java.lang.reflect.Method;

import java.security.KeyFactory;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

/**

* @program: guidePlus

* @description

* @author: Joker

* @create: 2021-04-15 11:50

**/

public class RSAUtil {

? ? public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {

? ? ? ? int keyByteSize = keyLength / 8;

? ? ? ? int decryptBlockSize = keyByteSize - reserveSize;

? ? ? ? int nBlock = encryptedBytes.length / keyByteSize;

? ? ? ? ByteArrayOutputStream outbuf = null;

? ? ? ? try {

? ? ? ? ? ? Cipher cipher = Cipher.getInstance(cipherAlgorithm);

? ? ? ? ? ? cipher.init(Cipher.DECRYPT_MODE, privateKey);

? ? ? ? ? ? outbuf = new ByteArrayOutputStream(nBlock * decryptBlockSize);

? ? ? ? ? ? for (int offset = 0; offset < encryptedBytes.length; offset += keyByteSize) {

? ? ? ? ? ? ? ? int inputLen = encryptedBytes.length - offset;

? ? ? ? ? ? ? ? if (inputLen > keyByteSize) {

? ? ? ? ? ? ? ? ? ? inputLen = keyByteSize;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? byte[] decryptedBlock = cipher.doFinal(encryptedBytes, offset, inputLen);

? ? ? ? ? ? ? ? outbuf.write(decryptedBlock);

? ? ? ? ? ? }

? ? ? ? ? ? outbuf.flush();

? ? ? ? ? ? return outbuf.toByteArray();

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? throw new Exception("DEENCRYPT ERROR:", e);

? ? ? ? } finally {

? ? ? ? ? ? try{

? ? ? ? ? ? ? ? if(outbuf != null){

? ? ? ? ? ? ? ? ? ? outbuf.close();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }catch (Exception e){

? ? ? ? ? ? ? ? outbuf = null;

? ? ? ? ? ? ? ? throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? public static byte[] encrypt(byte[] plainBytes, PublicKey publicKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {

? ? ? ? int keyByteSize = keyLength / 8;

? ? ? ? int encryptBlockSize = keyByteSize - reserveSize;

? ? ? ? int nBlock = plainBytes.length / encryptBlockSize;

? ? ? ? if ((plainBytes.length % encryptBlockSize) != 0) {

? ? ? ? ? ? nBlock += 1;

? ? ? ? }

? ? ? ? ByteArrayOutputStream outbuf = null;

? ? ? ? try {

? ? ? ? ? ? Cipher cipher = Cipher.getInstance(cipherAlgorithm);

? ? ? ? ? ? cipher.init(Cipher.ENCRYPT_MODE, publicKey);

? ? ? ? ? ? outbuf = new ByteArrayOutputStream(nBlock * keyByteSize);

? ? ? ? ? ? for (int offset = 0; offset < plainBytes.length; offset += encryptBlockSize) {

? ? ? ? ? ? ? ? int inputLen = plainBytes.length - offset;

? ? ? ? ? ? ? ? if (inputLen > encryptBlockSize) {

? ? ? ? ? ? ? ? ? ? inputLen = encryptBlockSize;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? byte[] encryptedBlock = cipher.doFinal(plainBytes, offset, inputLen);

? ? ? ? ? ? ? ? outbuf.write(encryptedBlock);

? ? ? ? ? ? }

? ? ? ? ? ? outbuf.flush();

? ? ? ? ? ? return outbuf.toByteArray();

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? throw new Exception("ENCRYPT ERROR:", e);

? ? ? ? } finally {

? ? ? ? ? ? try{

? ? ? ? ? ? ? ? if(outbuf != null){

? ? ? ? ? ? ? ? ? ? outbuf.close();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }catch (Exception e){

? ? ? ? ? ? ? ? outbuf = null;

? ? ? ? ? ? ? ? throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? public static PrivateKey getPriKey(String privateKeyPath,String keyAlgorithm){

? ? ? ? PrivateKey privateKey = null;

? ? ? ? InputStream inputStream = null;

? ? ? ? try {

? ? ? ? ? ? if(inputStream==null){

? ? ? ? ? ? ? ? System.out.println("hahhah1!");

? ? ? ? ? ? }

? ? ? ? ? ? inputStream = new FileInputStream(privateKeyPath);

? ? ? ? ? ? System.out.println("hahhah2!");

? ? ? ? ? ? privateKey = getPrivateKey(inputStream,keyAlgorithm);

? ? ? ? ? ? System.out.println("hahhah3!");

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? System.out.println("加載私鑰出錯!");

? ? ? ? } finally {

? ? ? ? ? ? if (inputStream != null){

? ? ? ? ? ? ? ? try {

? ? ? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? }catch (Exception e){

? ? ? ? ? ? ? ? ? ? System.out.println("加載私鑰,關(guān)閉流時出錯!");

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return privateKey;

? ? }

? ? public static PublicKey getPubKey(String publicKeyPath,String keyAlgorithm){

? ? ? ? PublicKey publicKey = null;

? ? ? ? InputStream inputStream = null;

? ? ? ? try

? ? ? ? {

? ? ? ? ? ? System.out.println("getPubkey 1......");

? ? ? ? ? ? inputStream = new FileInputStream(publicKeyPath);

? ? ? ? ? ? System.out.println("getPubkey 2......");

? ? ? ? ? ? publicKey = getPublicKey(inputStream,keyAlgorithm);

? ? ? ? ? ? System.out.println("getPubkey 3......");

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? e.printStackTrace();//EAD PUBLIC KEY ERROR

? ? ? ? ? ? System.out.println("加載公鑰出錯!");

? ? ? ? } finally {

? ? ? ? ? ? if (inputStream != null){

? ? ? ? ? ? ? ? try {

? ? ? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? }catch (Exception e){

? ? ? ? ? ? ? ? ? ? System.out.println("加載公鑰,關(guān)閉流時出錯!");

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return publicKey;

? ? }

? ? public static PublicKey getPublicKey(InputStream inputStream, String keyAlgorithm) throws Exception {

? ? ? ? try

? ? ? ? {

? ? ? ? ? ? System.out.println("b1.........");

? ? ? ? ? ? BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

? ? ? ? ? ? System.out.println("b2.........");

? ? ? ? ? ? StringBuilder sb = new StringBuilder();

? ? ? ? ? ? String readLine = null;

? ? ? ? ? ? System.out.println("b3.........");

? ? ? ? ? ? while ((readLine = br.readLine()) != null) {

? ? ? ? ? ? ? ? if (readLine.charAt(0) == '-') {

? ? ? ? ? ? ? ? ? ? continue;

? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? sb.append(readLine);

? ? ? ? ? ? ? ? ? ? sb.append('\r');

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? System.out.println("b4.........");

? ? ? ? ? ? X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(decodeBase64(sb.toString()));

? ? ? ? ? ? System.out.println("b5.........");

? ? ? ? ? ? KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);

? ? ? ? ? ? System.out.println("b6.........");

? ? ? ? ? ? //下行出錯? java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=127, too big.

? ? ? ? ? ? PublicKey publicKey = keyFactory.generatePublic(pubX509);

? ? ? ? ? ? System.out.println("b7.........");

? ? ? ? ? ? return publicKey;

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? System.out.println("b8.........");

? ? ? ? ? ? throw new Exception("READ PUBLIC KEY ERROR:", e);

? ? ? ? } finally {

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? if (inputStream != null) {

? ? ? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? } catch (IOException e) {

? ? ? ? ? ? ? ? inputStream = null;

? ? ? ? ? ? ? ? throw new Exception("INPUT STREAM CLOSE ERROR:", e);

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? public static PrivateKey getPrivateKey(InputStream inputStream, String keyAlgorithm) throws Exception {

? ? ? ? try {

? ? ? ? ? ? BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

? ? ? ? ? ? StringBuilder sb = new StringBuilder();

? ? ? ? ? ? String readLine = null;

? ? ? ? ? ? while ((readLine = br.readLine()) != null) {

? ? ? ? ? ? ? ? if (readLine.charAt(0) == '-') {

? ? ? ? ? ? ? ? ? ? continue;

? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? sb.append(readLine);

? ? ? ? ? ? ? ? ? ? sb.append('\r');

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? System.out.println("hahhah4!"+decodeBase64(sb.toString()));

? ? ? ? ? ? PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decodeBase64(sb.toString()));

? ? ? ? ? ? System.out.println("hahhah5!");

? ? ? ? ? ? KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);

? ? ? ? ? ? System.out.println("hahhah6!");

? ? ? ? ? ? PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);

? ? ? ? ? ? System.out.println("hahhah7!");

? ? ? ? ? ? return privateKey;

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? throw new Exception("READ PRIVATE KEY ERROR:" ,e);

? ? ? ? }? finally {

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? if (inputStream != null) {

? ? ? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? } catch (IOException e) {

? ? ? ? ? ? ? ? inputStream = null;

? ? ? ? ? ? ? ? throw new Exception("INPUT STREAM CLOSE ERROR:", e);

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? //一下面是base64的編碼和解碼

? ? public static String encodeBase64(byte[]input) throws Exception{

? ? ? ? Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");

? ? ? ? Method mainMethod= clazz.getMethod("encode", byte[].class);

? ? ? ? mainMethod.setAccessible(true);

? ? ? ? Object retObj=mainMethod.invoke(null, new Object[]{input});

? ? ? ? return (String)retObj;

? ? }

? ? /***

? ? * decode by Base64

? ? */

? ? public static byte[] decodeBase64(String input) throws Exception{

? ? ? ? Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");

? ? ? ? Method mainMethod= clazz.getMethod("decode", String.class);

? ? ? ? mainMethod.setAccessible(true);

? ? ? ? Object retObj=mainMethod.invoke(null, input);

? ? ? ? return (byte[])retObj;

? ? }

}

package com.qiouou.common.util.wxH5Pay;

import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.conn.ssl.SSLContexts;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;

import java.io.File;

import java.io.FileInputStream;

import java.security.KeyStore;

public class ClientCustomSSL {

? ? public static final? String URL = "XXXXXXX\apiclient_cert.p12";

? ? public static final String MERID = "XXXXXXX";

? ? public static String doRefund(String url,String data) throws Exception {

? ? ? ? /**

? ? ? ? * 注意PKCS12證書 是從微信商戶平臺-》賬戶設置-》 API安全 中下載的

? ? ? ? */

? ? ? ? KeyStore keyStore? = KeyStore.getInstance("PKCS12");

? ? ? ? FileInputStream instream = new FileInputStream(new File(URL));//P12文件目錄

? ? ? ? try {

? ? ? ? ? ? /**

? ? ? ? ? ? * 此處要改

? ? ? ? ? ? * */

? ? ? ? ? ? keyStore.load(instream, MERID.toCharArray());//這里寫密碼..默認是你的MCHID

? ? ? ? } finally {

? ? ? ? ? ? instream.close();

? ? ? ? }

? ? ? ? // Trust own CA and all self-signed certs

? ? ? ? /**

? ? ? ? * 此處要改

? ? ? ? * */

? ? ? ? SSLContext sslcontext = SSLContexts.custom()

? ? ? ? ? ? ? ? .loadKeyMaterial(keyStore, MERID.toCharArray())//這里也是寫密碼的

? ? ? ? ? ? ? ? .build();

? ? ? ? // Allow TLSv1 protocol only

? ? ? ? SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(

? ? ? ? ? ? ? ? sslcontext,

? ? ? ? ? ? ? ? new String[] { "TLSv1" },

? ? ? ? ? ? ? ? null,

? ? ? ? ? ? ? ? SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

? ? ? ? CloseableHttpClient httpclient = HttpClients.custom()

? ? ? ? ? ? ? ? .setSSLSocketFactory(sslsf)

? ? ? ? ? ? ? ? .build();

? ? ? ? try {

? ? ? ? ? ? HttpPost httpost = new HttpPost(url); // 設置響應頭信息

? ? ? ? ? ? httpost.addHeader("Connection", "keep-alive");

? ? ? ? ? ? httpost.addHeader("Accept", "*/*");

? ? ? ? ? ? httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

? ? ? ? ? ? httpost.addHeader("Host", "api.mch.weixin.qq.com");

? ? ? ? ? ? httpost.addHeader("X-Requested-With", "XMLHttpRequest");

? ? ? ? ? ? httpost.addHeader("Cache-Control", "max-age=0");

? ? ? ? ? ? httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

? ? ? ? ? ? httpost.setEntity(new StringEntity(data, "UTF-8"));

? ? ? ? ? ? CloseableHttpResponse response = httpclient.execute(httpost);

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? HttpEntity entity = response.getEntity();

? ? ? ? ? ? ? ? String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");

? ? ? ? ? ? ? ? EntityUtils.consume(entity);

? ? ? ? ? ? ? ? return jsonStr;

? ? ? ? ? ? } finally {

? ? ? ? ? ? ? ? response.close();

? ? ? ? ? ? }

? ? ? ? } finally {

? ? ? ? ? ? httpclient.close();

? ? ? ? }

? ? }

? ? /**

? ? * 企業(yè)微信支付到銀行卡

? ? * @param url

? ? * @param data

? ? * @return

? ? * @throws Exception

? ? */

? ? public static String paybank(String url,String data) throws Exception {

? ? ? ? /**

? ? ? ? * 注意PKCS12證書 是從微信商戶平臺-》賬戶設置-》 API安全 中下載的

? ? ? ? */

? ? ? ? KeyStore keyStore? = KeyStore.getInstance("PKCS12");

? ? ? ? FileInputStream instream = new FileInputStream(new File(URL));//P12文件目錄

? ? ? ? try {

? ? ? ? ? ? /**

? ? ? ? ? ? * 此處要改

? ? ? ? ? ? * */

? ? ? ? ? ? keyStore.load(instream, MERID.toCharArray());//這里寫密碼..默認是你的MCHID

? ? ? ? } finally {

? ? ? ? ? ? instream.close();

? ? ? ? }

? ? ? ? // Trust own CA and all self-signed certs

? ? ? ? /**

? ? ? ? * 此處要改

? ? ? ? * */

? ? ? ? SSLContext sslcontext = SSLContexts.custom()

? ? ? ? ? ? ? ? .loadKeyMaterial(keyStore, MERID.toCharArray())//這里也是寫密碼的

? ? ? ? ? ? ? ? .build();

? ? ? ? // Allow TLSv1 protocol only

? ? ? ? SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(

? ? ? ? ? ? ? ? sslcontext,

? ? ? ? ? ? ? ? new String[] { "TLSv1" },

? ? ? ? ? ? ? ? null,

? ? ? ? ? ? ? ? SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

? ? ? ? CloseableHttpClient httpclient = HttpClients.custom()

? ? ? ? ? ? ? ? .setSSLSocketFactory(sslsf)

? ? ? ? ? ? ? ? .build();

? ? ? ? try {

? ? ? ? ? ? HttpPost httpost = new HttpPost(url); // 設置響應頭信息

? ? ? ? ? ? httpost.addHeader("Connection", "keep-alive");

? ? ? ? ? ? httpost.addHeader("Accept", "*/*");

? ? ? ? ? ? httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

? ? ? ? ? ? httpost.addHeader("Host", "fraud.mch.weixin.qq.com");

? ? ? ? ? ? httpost.addHeader("X-Requested-With", "XMLHttpRequest");

? ? ? ? ? ? httpost.addHeader("Cache-Control", "max-age=0");

? ? ? ? ? ? httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

? ? ? ? ? ? httpost.setEntity(new StringEntity(data, "UTF-8"));

? ? ? ? ? ? CloseableHttpResponse response = httpclient.execute(httpost);

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? HttpEntity entity = response.getEntity();

? ? ? ? ? ? ? ? String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");

? ? ? ? ? ? ? ? EntityUtils.consume(entity);

? ? ? ? ? ? ? ? return jsonStr;

? ? ? ? ? ? } finally {

? ? ? ? ? ? ? ? response.close();

? ? ? ? ? ? }

? ? ? ? } finally {

? ? ? ? ? ? httpclient.close();

? ? ? ? }

? ? }

}

package com.qiouou.common.util.Wechat;

import org.apache.commons.codec.digest.DigestUtils;

import org.jdom2.Document;

import org.jdom2.Element;

import org.jdom2.input.SAXBuilder;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.*;

public class PayUtil {

? ? /**

? ? * 簽名字符串

? ? *

? ? * @param text? ? ? ? ? 需要簽名的字符串

? ? * @param key? ? ? ? ? 密鑰

? ? * @param input_charset 編碼格式

? ? * @return 簽名結(jié)果

? ? */

? ? public static String sign(String text, String key, String input_charset) {

? ? ? ? text = text + "&key=" + key;

? ? ? ? return DigestUtils.md5Hex(getContentBytes(text, input_charset));

? ? }

? ? /**

? ? * 簽名字符串

? ? *

? ? * @param text? ? ? ? ? 需要簽名的字符串

? ? * @param sign? ? ? ? ? 簽名結(jié)果

? ? * @param key? ? ? ? ? 密鑰

? ? * @param input_charset 編碼格式

? ? * @return 簽名結(jié)果

? ? */

? ? public static boolean verify(String text, String sign, String key, String input_charset) {

? ? ? ? text = text + key;

? ? ? ? String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));

? ? ? ? if (mysign.equals(sign)) {

? ? ? ? ? ? return true;

? ? ? ? } else {

? ? ? ? ? ? return false;

? ? ? ? }

? ? }

? ? /**

? ? * @param content

? ? * @param charset

? ? * @return

? ? * @throws java.security.SignatureException

? ? * @throws UnsupportedEncodingException

? ? */

? ? public static byte[] getContentBytes(String content, String charset) {

? ? ? ? if (charset == null || "".equals(charset)) {

? ? ? ? ? ? return content.getBytes();

? ? ? ? }

? ? ? ? try {

? ? ? ? ? ? return content.getBytes(charset);

? ? ? ? } catch (UnsupportedEncodingException e) {

? ? ? ? ? ? throw new RuntimeException("MD5簽名過程中出現(xiàn)錯誤,指定的編碼集不對,您目前指定的編碼集是:" + charset);

? ? ? ? }

? ? }

? ? private static boolean isValidChar(char ch) {

? ? ? ? if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))

? ? ? ? ? ? return true;

? ? ? ? if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))

? ? ? ? ? ? return true;// 簡體中文漢字編碼

? ? ? ? return false;

? ? }

? ? /**

? ? * 除去數(shù)組中的空值和簽名參數(shù)

? ? *

? ? * @param sArray 簽名參數(shù)組

? ? * @return 去掉空值與簽名參數(shù)后的新簽名參數(shù)組

? ? */

? ? public static Map<String, String> paraFilter(Map<String, String> sArray) {

? ? ? ? Map<String, String> result = new HashMap<String, String>();

? ? ? ? if (sArray == null || sArray.size() <= 0) {

? ? ? ? ? ? return result;

? ? ? ? }

? ? ? ? for (String key : sArray.keySet()) {

? ? ? ? ? ? String value = sArray.get(key);

? ? ? ? ? ? if (value == null || value.equals("") || key.equalsIgnoreCase("Sign")

? ? ? ? ? ? ? ? ? ? || key.equalsIgnoreCase("sign_type")) {

? ? ? ? ? ? ? ? continue;

? ? ? ? ? ? }

? ? ? ? ? ? result.put(key, value);

? ? ? ? }

? ? ? ? return result;

? ? }

? ? /**

? ? * 把數(shù)組所有元素排序到旦,并按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串

? ? *

? ? * @param params 需要排序并參與字符拼接的參數(shù)組

? ? * @return 拼接后字符串

? ? */

? ? public static String createLinkString(Map<String, String> params) {

? ? ? ? List<String> keys = new ArrayList<>(params.keySet());

? ? ? ? Collections.sort(keys);

? ? ? ? String prestr = "";

? ? ? ? for (int i = 0; i < keys.size(); i++) {

? ? ? ? ? ? String key = keys.get(i);

? ? ? ? ? ? String value = params.get(key);

? ? ? ? ? ? if (i == keys.size() - 1) {// 拼接時,不包括最后一個&字符

? ? ? ? ? ? ? ? prestr = prestr + key + "=" + value;

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? prestr = prestr + key + "=" + value + "&";

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return prestr;

? ? }

? ? /**

? ? * @param requestUrl? ? 請求地址

? ? * @param requestMethod 請求方法

? ? * @param outputStr? ? 參數(shù)

? ? */

? ? public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {

? ? ? ? // 創(chuàng)建SSLContext

? ? ? ? StringBuffer buffer = null;

? ? ? ? try {

? ? ? ? ? ? URL url = new URL(requestUrl);

? ? ? ? ? ? HttpURLConnection conn = (HttpURLConnection) url.openConnection();

? ? ? ? ? ? conn.setRequestMethod(requestMethod);

? ? ? ? ? ? conn.setDoOutput(true);

? ? ? ? ? ? conn.setDoInput(true);

? ? ? ? ? ? conn.connect();

? ? ? ? ? ? //往服務器端寫內(nèi)容

? ? ? ? ? ? if (null != outputStr) {

? ? ? ? ? ? ? ? OutputStream os = conn.getOutputStream();

? ? ? ? ? ? ? ? os.write(outputStr.getBytes("utf-8"));

? ? ? ? ? ? ? ? os.close();

? ? ? ? ? ? }

? ? ? ? ? ? // 讀取服務器端返回的內(nèi)容

? ? ? ? ? ? InputStream is = conn.getInputStream();

? ? ? ? ? ? InputStreamReader isr = new InputStreamReader(is, "utf-8");

? ? ? ? ? ? BufferedReader br = new BufferedReader(isr);

? ? ? ? ? ? buffer = new StringBuffer();

? ? ? ? ? ? String line = null;

? ? ? ? ? ? while ((line = br.readLine()) != null) {

? ? ? ? ? ? ? ? buffer.append(line);

? ? ? ? ? ? }

? ? ? ? ? ? br.close();

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? ? ? return buffer.toString();

? ? }

? ? public static String urlEncodeUTF8(String source) {

? ? ? ? String result = source;

? ? ? ? try {

? ? ? ? ? ? result = java.net.URLEncoder.encode(source, "UTF-8");

? ? ? ? } catch (UnsupportedEncodingException e) {

? ? ? ? ? ? // TODO Auto-generated catch block

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? ? ? return result;

? ? }

? ? /**

? ? * 解析xml,返回第一級元素鍵值對巨缘。如果第一級元素有子節(jié)點添忘,則此節(jié)點的值是子節(jié)點的xml數(shù)據(jù)。

? ? *

? ? * @param strxml

? ? * @return

? ? * @throws org.jdom2.JDOMException

? ? * @throws IOException

? ? */

? ? public static Map doXMLParse(String strxml) throws Exception {

? ? ? ? if (null == strxml || "".equals(strxml)) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? Map m = new HashMap();

? ? ? ? InputStream in = String2Inputstream(strxml);

? ? ? ? SAXBuilder builder = new SAXBuilder();

? ? ? ? Document doc = builder.build(in);

? ? ? ? Element root = doc.getRootElement();

? ? ? ? List list = root.getChildren();

? ? ? ? Iterator it = list.iterator();

? ? ? ? while (it.hasNext()) {

? ? ? ? ? ? Element e = (Element) it.next();

? ? ? ? ? ? String k = e.getName();

? ? ? ? ? ? String v = "";

? ? ? ? ? ? List children = e.getChildren();

? ? ? ? ? ? if (children.isEmpty()) {

? ? ? ? ? ? ? ? v = e.getTextNormalize();

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? v = getChildrenText(children);

? ? ? ? ? ? }

? ? ? ? ? ? m.put(k, v);

? ? ? ? }

? ? ? ? //關(guān)閉流

? ? ? ? in.close();

? ? ? ? return m;

? ? }

? ? /**

? ? * 獲取子結(jié)點的xml

? ? *

? ? * @param children

? ? * @return String

? ? */

? ? public static String getChildrenText(List children) {

? ? ? ? StringBuffer sb = new StringBuffer();

? ? ? ? if (!children.isEmpty()) {

? ? ? ? ? ? Iterator it = children.iterator();

? ? ? ? ? ? while (it.hasNext()) {

? ? ? ? ? ? ? ? Element e = (Element) it.next();

? ? ? ? ? ? ? ? String name = e.getName();

? ? ? ? ? ? ? ? String value = e.getTextNormalize();

? ? ? ? ? ? ? ? List list = e.getChildren();

? ? ? ? ? ? ? ? sb.append("<" + name + ">");

? ? ? ? ? ? ? ? if (!list.isEmpty()) {

? ? ? ? ? ? ? ? ? ? sb.append(getChildrenText(list));

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? sb.append(value);

? ? ? ? ? ? ? ? sb.append("</" + name + ">");

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return sb.toString();

? ? }

? ? public static InputStream String2Inputstream(String str) {

? ? ? ? return new ByteArrayInputStream(str.getBytes());

? ? }

}

package com.qiouou.common.util.wxH5Pay;

import java.security.MessageDigest;

public class MD5Utils {

? ? /**

? ? * MD5

? ? * @param buffer

? ? * @return

? ? */

? ? public final static String getMessageDigest(byte[] buffer) {

? ? ? ? char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

? ? ? ? try {

? ? ? ? ? ? MessageDigest mdTemp = MessageDigest.getInstance("MD5");

? ? ? ? ? ? mdTemp.update(buffer);

? ? ? ? ? ? byte[] md = mdTemp.digest();

? ? ? ? ? ? int j = md.length;

? ? ? ? ? ? char str[] = new char[j * 2];

? ? ? ? ? ? int k = 0;

? ? ? ? ? ? for (int i = 0; i < j; i++) {

? ? ? ? ? ? ? ? byte byte0 = md[i];

? ? ? ? ? ? ? ? str[k++] = hexDigits[byte0 >>> 4 & 0xf];

? ? ? ? ? ? ? ? str[k++] = hexDigits[byte0 & 0xf];

? ? ? ? ? ? }

? ? ? ? ? ? return new String(str);

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末若锁,一起剝皮案震驚了整個濱河市搁骑,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖仲器,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件煤率,死亡現(xiàn)場離奇詭異,居然都是意外死亡乏冀,警方通過查閱死者的電腦和手機涕侈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來煤辨,“玉大人,你說我怎么就攤上這事木张≈诒妫” “怎么了?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵舷礼,是天一觀的道長鹃彻。 經(jīng)常有香客問我,道長妻献,這世上最難降的妖魔是什么蛛株? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮育拨,結(jié)果婚禮上谨履,老公的妹妹穿的比我還像新娘。我一直安慰自己熬丧,他們只是感情好笋粟,可當我...
    茶點故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著析蝴,像睡著了一般害捕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上闷畸,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天尝盼,我揣著相機與錄音,去河邊找鬼佑菩。 笑死盾沫,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的殿漠。 我是一名探鬼主播疮跑,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼凸舵!你這毒婦竟也來了祖娘?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎渐苏,沒想到半個月后掀潮,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡琼富,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年仪吧,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鞠眉。...
    茶點故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡薯鼠,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出械蹋,到底是詐尸還是另有隱情出皇,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布哗戈,位于F島的核電站郊艘,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏唯咬。R本人自食惡果不足惜纱注,卻給世界環(huán)境...
    茶點故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望胆胰。 院中可真熱鬧狞贱,春花似錦、人聲如沸蜀涨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽勉盅。三九已至佑颇,卻和暖如春腮出,著一層夾襖步出監(jiān)牢的瞬間就轧,已是汗流浹背犬绒。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工啃奴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留惨篱,地道東北人辛块。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓摘完,卻偏偏與公主長得像沼头,于是被迫代替她去往敵國和親移袍。 傳聞我的和親對象是個殘疾皇子解藻,可洞房花燭夜當晚...
    茶點故事閱讀 45,870評論 2 361

推薦閱讀更多精彩內(nèi)容