package com.oying.modules.hwc.utils;
|
|
import org.dom4j.Document;
|
import org.dom4j.DocumentException;
|
import org.dom4j.Element;
|
import org.dom4j.io.SAXReader;
|
import org.xml.sax.InputSource;
|
|
import java.io.StringReader;
|
import java.net.URLEncoder;
|
import java.util.*;
|
|
|
/**
|
* ClassName:SignUtils
|
* Function: 签名用的工具箱
|
* Date: 2014-6-27 下午3:22:33
|
*/
|
public class SignUtils {
|
|
/**
|
* <一句话功能简述>
|
* <功能详细描述>验证返回参数
|
*
|
* @see [类、类#方法、类#成员]
|
*/
|
public static boolean checkParam(Map<String, String> params, String key) {
|
boolean result = false;
|
if (params.containsKey("sign")) {
|
String sign = params.get("sign");
|
params.remove("sign");
|
StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
|
SignUtils.buildPayParams(buf, params, false);
|
String preStr = buf.toString();
|
String signMD5 = MD5.sign(preStr, "&key=" + key, "utf-8");
|
result = sign.equalsIgnoreCase(signMD5);
|
}
|
return result;
|
}
|
|
/**
|
* 过滤参数
|
*/
|
public static Map<String, String> paraFilter(Map<String, String> sArray) {
|
Map<String, String> result = new HashMap<>(sArray.size());
|
if (sArray.isEmpty()) {
|
return result;
|
}
|
for (String key : sArray.keySet()) {
|
String value = sArray.get(key);
|
if (value == null || value.isEmpty() || key.equalsIgnoreCase("sign")) {
|
continue;
|
}
|
result.put(key, value);
|
}
|
return result;
|
}
|
|
/**
|
* <一句话功能简述>
|
* <功能详细描述>将map转成String
|
*
|
* @see [类、类#方法、类#成员]
|
*/
|
public static String payParamsToString(Map<String, String> payParams) {
|
return payParamsToString(payParams, false);
|
}
|
|
public static String payParamsToString(Map<String, String> payParams, boolean encoding) {
|
return payParamsToString(new StringBuilder(), payParams, encoding);
|
}
|
|
public static String payParamsToString(StringBuilder sb, Map<String, String> payParams, boolean encoding) {
|
buildPayParams(sb, payParams, encoding);
|
return sb.toString();
|
}
|
|
public static void buildPayParams(StringBuilder sb, Map<String, String> payParams, boolean encoding) {
|
List<String> keys = new ArrayList<>(payParams.keySet());
|
Collections.sort(keys);
|
for (String key : keys) {
|
sb.append(key).append("=");
|
if (encoding) {
|
sb.append(urlEncode(payParams.get(key)));
|
} else {
|
sb.append(payParams.get(key));
|
}
|
sb.append("&");
|
}
|
sb.setLength(sb.length() - 1);
|
}
|
|
public static String urlEncode(String str) {
|
try {
|
return URLEncoder.encode(str, "UTF-8");
|
} catch (Throwable e) {
|
return str;
|
}
|
}
|
|
public static Element readerXml(String body, String encode) throws DocumentException {
|
SAXReader reader = new SAXReader(false);
|
InputSource source = new InputSource(new StringReader(body));
|
source.setEncoding(encode);
|
Document doc = reader.read(source);
|
return doc.getRootElement();
|
}
|
|
}
|