MD5Util.java
2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.erry.iclear.dateInterface.util;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
/**
* @author Administrator
*/
public class MD5Util {
private static Log logger = LogFactory.getLog(MD5Util.class);
public static String md5(String inStr) {
try {
return DigestUtils.md5Hex(inStr.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误");
}
}
public static String sign(Map<String, Object> params, String appSecret) {
StringBuilder valueSb = new StringBuilder();
// 将参数以参数名的字典升序排序
Map<String, Object> sortParams = new TreeMap<String, Object>(params);
Set<Entry<String, Object>> entrys = sortParams.entrySet();
// 遍历排序的字典,并拼接value1+value2......格式
for (Entry<String, Object> entry : entrys) {
valueSb.append(entry.getValue());
}
valueSb.append(appSecret);
return md5(valueSb.toString());
}
public static String getParam(JSONObject jsonObj, StringBuffer sb) {
if(jsonObj.get("sign")!=null){
jsonObj.remove("sign");
}
// 将参数以参数名的字典升序排序
for (Entry<String, Object> entry : jsonObj.entrySet()) {
try{
JSONArray array = JSONArray.parseArray(entry.getValue().toString());
if(array!=null) {
for (int i = 0; i < array.size(); i++) {
getParam(array.getJSONObject(i), sb);
}
}
}catch (JSONException e){
try{
JSONObject obj = JSONObject.parseObject(entry.getValue().toString());
getParam(obj,sb);
}catch (JSONException E2){
sb.append(entry.getValue());
}
}
}
return sb.toString();
}
public static String md5(Object inStr,String key) {
try {
JSONObject json = JSON.parseObject(JSONObject.toJSONString(inStr), Feature.OrderedField);
String str = MD5Util.getParam(json,new StringBuffer());
return DigestUtils.md5Hex((str+key).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误");
}
}
}