签名生成 参数列表(Map、List)ASCII码从小到大排序(字典顺序)

生成签名遇到的两种场景,做下记录。

参数列表为LIst

ArrayList<String> list = new ArrayList<>();
list.add(age);
list.add(name);
list.add(hobb);
String signByList = getSignByList(list);
System.out.println(signByList);

public static String getSignByList(ArrayList<String> list) {

    // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
    list.sort(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });
    // 构造签名键值对的格式
    StringBuilder sb = new StringBuilder();
    for(String ss:list){
        sb.append(ss+"&");
    }
    return sb.toString();
}
// 下面是输出结果:
// 16&John&book&

参数列表为Map

Map map = new HashMap();
map.put("age",age);
map.put("name",name);
map.put("hobb",hobb);
String sign = getSign(map);
public static String getSign(Map<String, String> map) {

    String result = "";
    try {
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
        infoIds.sort(new Comparator<Map.Entry<String, String>>() {
        public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
            return (o1.getKey()).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();
    } catch (Exception e) {
        return null;
    }
    return result;
}
// 下面是输出结果:
// age=16&hobb=book&name=John&

//还可以直接放TreeMap中

Map<String ,String > map = new TreeMap<String,String>();
map.put("qwe","123");
map.put("asd","456");
map.put("zxc","789");
StringBuilder str = new StringBuilder();
for(String mm : map.keySet()){
    str.append(mm).append("=").append(map.get(mm)).append("&");
}
String msg = str.substring(0,str.length()-1).toString();
System.out.println(msg);

关于生成签名后的加密

你可能感兴趣的:(java)