Map集合Key 按照ASCII碼從小到大(字典序)排序

/**
 * 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章