软件工程师成长日记

Map集合按照ASCII码从小到大(字典序)排序--JAVA

2018-06-21  本文已影响4人  麦克劳林

以下代码:将传参按照ASCII 码字典序排序,并将生成的字符串进行MD5加密

/**
 * Description:MD5工具生成token
 * @param value
 * @return
 */
public String getMD5Value(String value){
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] md5ValueByteArray = messageDigest.digest(value.getBytes());
        BigInteger bigInteger = new BigInteger(1 , md5ValueByteArray);
        return bigInteger.toString(16).toUpperCase();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
/**
 * 生成签名
 * @param map
 * @return
 */
public String getSignToken(Map<String, String> map) {
    String result = "";
    try {
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });
        // 构造签名键值对的格式
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> item : infoIds) {
            if (item.getKey() != null || item.getKey() != "") {
                String key = item.getKey();
                String val = item.getValue();
                if (!(val == "" || val == null)) {
                    sb.append(key + "=" + val + "&");
                }
            }
        }
        result = sb.toString();
        //进行MD5加密
        result = getMD5Value(result);
    } catch (Exception e) {
        return null;
    }
    return result;
}
上一篇下一篇

猜你喜欢

热点阅读