Pu Zhibing
2025-05-09 8580866e175ad0050ee9c5ea3f757856fc242c39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.stylefeng.guns.modular.system.util;
 
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
 
import java.util.Map;
import java.util.TreeMap;
 
@Slf4j
public class SignUtil {
 
    public static String sign(String appKey, String ts, String appSecret, Object body) {
        log.debug("appKey:{}, ts:{}, appSecret:{}, body:{}", appKey, ts, appSecret,
                JSON.toJSONString(body));
        //0. 使⽤ Hutools 包JSON处理 Bean 2 Map
        Map<String, Object> bodyMap = new JSONObject(body);
        // 1. remove sign parameter
        bodyMap.entrySet().removeIf(entry -> entry.getValue() == null);
        // 2. 把字典按Key的字⺟顺序排序
        Map<String, Object> treeMap = new TreeMap<>(bodyMap);
        // 3. 把参数串起来
        StringBuffer origin = new StringBuffer(appSecret).append("appKey")
                .append(appKey);
        treeMap.forEach((key, value) -> origin.append(key).append(value));
        origin.append("ts");
        // 4. 加密:MD5 + ⼤写&⼗六进制
        String result = null;
        String s = null;
        log.debug("SecretString Origin: {}", origin.toString());
        try {
            s = origin.toString();
            result = MD5Util.encrypt32(s);
        } catch (Exception e) {
            log.error("md5加密错误,origin: {}", s, e);
        }
        log.debug("Signature Result: {}", result);
        return result;
    }
 
}