Java签名

public class SignUtils {

    public static void main(String[] args) throws Exception {
        TreeMap<String, String> params = new TreeMap<>();
        params.put("account", "13469967652");
        params.put("timestamp", "1595235495256");
        params.put("appId", "31476");
        params.put("password", "b8983c077f2690b76c96c49641f148b0");
        System.out.println(getSign("https://api.clife.cn/v1/account/login", "POST", "46cb70d61e34437ba24e2a99b89b5cf7", params, false));
    }

    public static String getSignFromObj(Object object, String api, String httpMethod, String appSecret, boolean upperOrLower) throws Exception {

        Class clazz = object.getClass();

        Field[] declaredFields = clazz.getDeclaredFields();

        Map<String, String> params = new TreeMap<>();

        for (Field declaredField : declaredFields) {
            if (Modifier.isStatic(declaredField.getModifiers()) || Modifier.isFinal(declaredField.getModifiers()) || Modifier.isTransient(declaredField.getModifiers())) {
                continue;
            }
            declaredField.setAccessible(true);
            Object value = declaredField.get(object);
            if (value == null) {
                value = "";
            }
            params.put(declaredField.getName(), value.toString());
        }

        params.remove("sign");

        StringBuilder buf = new StringBuilder();
        buf.append(httpMethod).append(api);
        for (Map.Entry<String, String> param : params.entrySet()) {
            buf.append(param.getKey()).append("=").append(param.getValue()).append("&");
        }
        buf.append(appSecret);
        String sign = DigestUtils.md5Hex(buf.toString());
        if (upperOrLower) {
            return StringUtils.upperCase(sign);
        }
        return sign;
    }

    public static String getSign(String api, String httpMethod, String appSecret, TreeMap<String, String> params, boolean upperOrLower) throws Exception {


        StringBuilder buf = new StringBuilder();
        buf.append(httpMethod).append(api);
        for (Map.Entry<String, String> param : params.entrySet()) {
            buf.append(param.getKey()).append("=").append(param.getValue()).append("&");
        }
        buf.append(appSecret);
        String data = buf.toString();
        System.out.println(data);
        String sign = DigestUtils.md5Hex(data);
        if (upperOrLower) {
            return StringUtils.upperCase(sign);
        }
        return sign;
    }
}

你可能感兴趣的:(代码工具)