novoland
12/11/2017 - 6:31 AM

点评 open api 生成 sign

点评 open api 生成 sign

public static void main(String[] args) throws Exception{
    Map<String, String> params = new HashMap<>();
    params.put("timestamp","2017-12-10 14:37:40");
    params.put("session","c1fc1773a27d47e988725bc6df150626dbda0b4d");
    params.put("format","json");
    params.put("sign_method","MD5");
    params.put("app_key","1000055");
    params.put("v", "1");

    params.put("latitude", "1");
    params.put("longitude", "1");
    params.put("deviceId", "1");
    System.out.println(signTopRequest(params, "4e0d1be81540c4d1f0868d329b3229467f071f6c", "MD5"));
}

public static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException, NoSuchAlgorithmException { // 第一步:检查参数是否已经排序
    String[] keys = params.keySet().toArray(new String[0]);
    Arrays.sort(keys);
    // 第二步:把所有参数名和参数值串在一起
    StringBuilder query = new StringBuilder();
    query.append(secret);

    for (String key : keys) {
        String value = params.get(key);
        query.append(key).append(value);
    }

    // 第三步:使用MD5/HMAC加密
    byte[] bytes;
    query.append(secret);
    bytes = encryptMD5(query.toString());

    // 第四步:把二进制转化为小写的十六进制
    return byte2hex(bytes);
}


public static byte[] encryptMD5(String info) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    byte[] infoBytes = info.getBytes();
    md5.update(infoBytes);
    return md5.digest();
}


public static String byte2hex(byte[] bytes) {
    StringBuilder sign = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(bytes[i] & 0xFF);
        if (hex.length() == 1) {
            sign.append("0");
        }
        sign.append(hex.toLowerCase());
    }
    return sign.toString();
}