设所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA。
在stringA最后拼接上key得到stringSignTemp字符串,并对stringSignTemp进行HMAC-SHA256运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。
第一步:对参数按照key=value的格式,并按照参数名ASCII字典序排序如下:
stringA="channelId=mttest&body=test×tamp=1516320000000";
第二步:拼接API密钥:
stringSignTemp=stringA+"&secret=my_test_secret"
sign=hash_hmac("sha256",stringSignTemp,key).toUpperCase()="6A9AE1657590FD6257D693A078E1C3E4BB6BA4DC30B23E0EE2496E54170DACD6" //注:HMAC-SHA256签名方式
@Test
public void deductBalance() throws IOException {
JTextField field ;
String url = "http://localhost:8088/channel/deductBalance";
//Java中的TreeMap会自动将key按照以ASCII字典进行排序
TreeMap<String,Object> params = Maps.newTreeMap();
params.put("orderId","my_order_id");
params.put("channelId","test91021071617412");
long timestamp = System.currentTimeMillis();
params.put("timestamp",timestamp);
String channelSign = getChannelSign(params, secret);
params.put("sign",channelSign);
System.out.println(url);
System.out.println(JSON.toJSONString(params));
String result = HttpUtils.sendRequestBody(url, params);
System.out.println(result);
}
public static String getChannelSign(Map<String, Object> params,String secret) {
StringBuilder result = new StringBuilder();
if (params != null) {
for (Object key : params.keySet()) {
Object value = params.get(key);
result.append(key).append("=").append(value).append("&");
}
String tempString = result + "secret=" + secret;
try {
System.out.println(tempString);
String sign = EncryptUtils.sha256_HMAC(tempString, secret).toUpperCase();
System.out.println(sign);
return sign;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
代码中参与加密的参数及顺序为:channelId=test91021071617412&orderId=my_test_id×tamp=1547987604644&secret=my_secret