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

以下代码:将传参按照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 map) {
    String result = "";
    try {
        List> infoIds = new ArrayList>(map.entrySet());
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
        Collections.sort(infoIds, new Comparator>() {

            public int compare(Map.Entry o1, Map.Entry o2) {
                return (o1.getKey()).toString().compareTo(o2.getKey());
            }
        });
        // 构造签名键值对的格式
        StringBuilder sb = new StringBuilder();
        for (Map.Entry 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;
}

你可能感兴趣的:(Map集合按照ASCII码从小到大(字典序)排序--JAVA)