tools.utils.GenerateSign Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-autotest-tool Show documentation
Show all versions of java-autotest-tool Show documentation
This is an integration of autotest tools
package tools.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import tools.json.AutoComparation;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class GenerateSign {
private static final Charset UTF_8 = StandardCharsets.UTF_8;
private static final String securityKey = "6dd0726180c9504132bb47fcee33a9d9";
public static String getSignStr(Map params) {
List paramStr = new ArrayList<>(params.size());
for (String key : params.keySet()) {
paramStr.add(key + "=" + params.get(key));
}
Collections.sort(paramStr);
return String.join("&", paramStr);
}
public static String getSignStr(JSONObject jsonObject) {
List paramStrList = new ArrayList<>();
System.out.println(JSON.toJSONString(jsonObject, true));
AutoComparation.setKeyValueToList(jsonObject, paramStrList);
System.out.println(paramStrList);
Collections.sort(paramStrList);
System.out.println(paramStrList);
return String.join("&", paramStrList);
}
public static String generateSign(String content, String algorithm) {
content += securityKey;
MessageDigest md;
try {
md = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
return bytesToHex(md.digest(content.getBytes(UTF_8)));
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public static void main(String[] args) {
JSONObject requestParamJSONObject = new JSONObject(true);
requestParamJSONObject.put("user_id", 45507);
requestParamJSONObject.put("role_id", 45507);
// long timestamp = SignUtil.getTimestampAsMilliSecond();
requestParamJSONObject.put("timestamp", 1615865008940L);
requestParamJSONObject.put("sign_type", "MD5");
requestParamJSONObject.put("version", "2.0");
requestParamJSONObject.put("app_id", 50030393);
JSONObject network_conf_object = new JSONObject(true);
network_conf_object.put("network", 1);
network_conf_object.put("app_id", 50030393);
network_conf_object.put("app_key", "new app_key");
requestParamJSONObject.put("network_conf", network_conf_object);
Map map = new HashMap<>();
for (String key : requestParamJSONObject.keySet()){
map.put(key, String.valueOf(requestParamJSONObject.get(key)));
}
System.out.println(map);
System.out.printf("sign: %s\n", generateSign(getSignStr(map), "MD5"));
}
}