签名验签
本文档主要讲解签名算法
一、签名计算过程
1、将请求数据中的参数按照参数名ASCII码从小到大排序(字典序),用参数名和参数值组成键值对,并通过连接符"&"拼接
键值对格式:key=value
连接后的字符串样例:a=1&b=2&c=3×tamp=1573554164295
2、将连接后的字符串,按照HmacSHA1算法计算签名,算法密钥为appSecret
3、将HmacSHA1加密之后的结果转BASE64编码
4、签名算法计算出来的字符串为签名值sign
特殊说明
发送请求之前使用UTF-8进行URLEncoding处理
- 样例:
参数拼接后的字符串:a=1&b=2&c=3×tamp=1573554164295 签名密钥appSecret = sE%lU%qLNhSy*kliM#DO 签名结果sign = 6r5WdYygMCaXRyirnkGTFvBZQvA=
二、签名算法 java版demo
/**
* 请求参数排序
*
* @param map 请求参数map
* @return
*/
public static String paramSort(Map<String, String> map) {
List<String> keys = new ArrayList<>(map.keySet());
Collections.sort(keys);
StringBuilder prestr = new StringBuilder();
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = map.get(key);
if (i == keys.size() - 1) {
prestr.append(key).append("=").append(value);
} else {
prestr.append(key).append("=").append(value).append("&");
}
}
return prestr.toString();
}
/**
* 签名算法
*
* @param content 签名明文
* @param key 应用密钥
* @return 签名信息
* @throws Exception
*/
public static String hmacSha1Encrypt(String content, String key) throws Exception {
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
SecretKeySpec localSecretKeySpec = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac localMac = Mac.getInstance("HmacSHA1");
localMac.init(localSecretKeySpec);
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
localMac.update(contentBytes);
return Base64.encodeBase64String(localMac.doFinal());
}