package net.joystart.common.util;
import java.security.MessageDigest;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import sun.misc.BASE64Encoder;
public class MD5SignUtil {
private Map<String, String> map = new HashMap<String, String>();
/**
* @Description: 签名构造函数
* @author FFCS
* @param <header>:iCtrlCmdId sUserKey sVin lTime
* @param <body>:oCtrl(data)
* @param privateKey(云度私下提供)
* @time 2017/10/12
* */
public MD5SignUtil(String iCtrlCmdId, String sUserKey, String sVin, String lTime, Map<String, String> oCtrl,String privateKey) {
Map<String, String> mapShort = new HashMap<String, String>();
mapShort.put("iCtrlCmdId", iCtrlCmdId);
mapShort.put("sUserKey", sUserKey);
mapShort.put("sVin", sVin);
mapShort.put("lTime", lTime);
mapShort.put("privateKey",privateKey);
mapShort.putAll(oCtrl);
map=sortMapByKey(mapShort); //使用 Map按key进行排序
}
/**
* @Description: 获取签名
* @author FFCS
* @param
* @time 2017/10/12
* */
public String sign() throws Exception {
String s = "";
for (Map.Entry<String, String> entry : map.entrySet()) {
s += entry.getKey();
s += "=";
s +=entry.getValue();
}
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64 = new BASE64Encoder();
String sign = base64.encode(md5.digest(s.getBytes("utf-8")));
return sign;
}
/**
* 使用 Map按key进行排序
* @param map
* @return
*/
public static Map<String, String> sortMapByKey(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
}
//比较器类
class MapKeyComparator implements Comparator<String>{
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}