跳到主要内容

签名方法

所有Api接口请求和接收数据均需要校验签名,

  • 签名算法:MD5

对所有API请求参数(包括公共参数和业务参数,但除去sign参数),根据参数名称的ASCII码表的顺序排序。如:a=1, c=3, b=2 排序后的顺序是 a=1, b=2,c=3。

将排序好的参数名和参数值按url拼装方式拼接在一起,根据上面的示例得到的结果为:

a=1&b=3&c=2

在拼装的字符串后加上secret_key后,采用utf-8编码, 再进行MD5摘要,如deviceSecret=xxxx,可以得到

md5(a=1&b=3&c=2&deviceSecret=xxxx) 
信息

什么是 设备deviceSecret

将摘要得到的字节流结果使用十六进制表示,并转换成大写。如

hex("helloworld".getBytes("utf-8")).toUpperCase() = "68656C6C6F776F726C64"

签名示例

import org.apache.commons.lang3.StringUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SignUtils {
public static String md5Sign(Map<String, String> params, String secretKey) {
List<String> keys = Lists.newArrayList();
for (Map.Entry<String, String> entry : params.entrySet()) {
if ("sign".equals(entry.getKey())) {
continue;
}
if (StringUtils.isNotBlank(entry.getValue())) {
keys.add(entry.getKey());
}
}
Collections.sort(keys);

List<String> temp = Lists.newArrayList();
for (String key : keys) {
String value = params.get(key);
temp.add(key + "=" + value);
}

temp.add("deviceSecret=" + secretKey);
String signStr = StringUtils.join(temp, "&");
return genMd5(signStr);
}

public static String genMd5(String info) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}

byte[] infoBytes = info.getBytes();
md5.update(infoBytes);
byte[] sign = md5.digest();
return byteArrayToHex(sign);
}

public static String byteArrayToHex(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.toUpperCase());
}
return sign.toString();
}
}