java
package com.example.test;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;
import java.util.TreeMap;
class SignService {
public static void main(String[] args) throws NoSuchAlgorithmException {
Hashtable ht = new Hashtable();
ht.put("biz", "{\"page_index\":\"1\",\"page_size\":\"100\",\"nicks\":[\"老来"]}");
ht.put("charset", "utf-8");
ht.put("app_key", "5b53060f2375643423056e84fa5a2d");
ht.put("access_token", "d7b01bf084ghdgsf21ffd95f60");
ht.put("timestamp", "153428407");
ht.put("version", "2");
String sign = getSign("99c4cef678545gfds975a7064de0b87", ht);
System.out.println(sign);
}
static String getSign(String signKey, Hashtable param) throws NoSuchAlgorithmException {
//使用TreeMap对Hashtable的键进行排序
TreeMap<String, String> sortedMap = new TreeMap<>(param);
String resultStr = "";
for (String key : sortedMap.keySet()) {
if (key != null && key != "" && key != "sign") {
resultStr = resultStr + key + param.get(key);
}
}
resultStr = signKey + resultStr;
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] rstRes = md.digest(resultStr.getBytes(StandardCharsets.UTF_8));
// 将字节数组转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : rstRes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
// 返回32个字符长度的十六进制字符串
return hexString.toString();
}
}
需要把下面这一串信息 试用MD5算法 加密 然后转化成32
签名算法:
以执行店铺查询htps:/openahn,.cm/on/shps/qury为例,假如开发者的app_secret是e9c5ca3334534d0ef4a6d25,请求的参数如下:
app_key:5b53060f23d3453056e84fa5a2d
access token:d7b01bf345a9450e21ffd95f60
timestamp:163458407
version:0
charset:utf-8
sign:395f5a78b4756403a02491296c7
biz:{"page_index":"1","page_size":"100","niks":["豆腐干"]}
步骤:
1.将请求参数中除 sign 外的多个键值对,根据键按照字典序排序,并按照"key1value1key2value2..."的格式拼成一个字符串。请求参数拼接后的结果为:acces tokend7b01b0842a4746554fd95f60app key5b53060f452332d9703056e84fa5a2dbiz"page index:"1""pae sire": 100,"niks":["板"icharsetutf-8timestamp16391567407version21
2.将 app_secret 拼接在1中排序后的字符串前面得到待签名字符串:e9csca3fecb404b756864343bd0ef4a6d25aces tokend7b01bf04359450e21fd95f60app key$b53060f45323df9703056e84fa5a2dbizl page index."1"page size. 10"niks :"t"icharsetutf8timestamp166345407version21
3.使用 MD5 算法加密待加密字符串并转为32位小写即为 sign: 395f5a78b7865434ac03a02491296c74.将 sign 添加到请求参数中
注意:
1.对于biz这类复杂参数,不论value内部是否包含多个字段,均把value看作-个完整字符串来处理,不需要对内部字段进行拆分和排序,2.请求参数中有中文时,中文需要经过 ur 编码,但计算签名时不需要。3.计算 MD5 签名时,需要以 utf-8 的编码转换 byte 流,否则可能导致含中文参数的签名计算不正确