签名方式
说明
签名使用算法为 HmacSHA256
第一步 将 应用id(appId) 与 当前时间戳(timestamp) 与 请求路径加post请求的body 三者用点拼接.
- 如
- 应用id(appId)为: 102
- 当前时间(timestamp)为:1596794830559
- 请求路径(path)为:/api/v1/device/getDeviceInfo
- 内容(body)为: {“corpId”:”12345678123456781234567812345678”,”deviceNo”:”800xxxxxxxx1234”}
- 那么拼装后为 102.1596794830559./api/v1/device/getDeviceInfo{“corpId”:”12345678123456781234567812345678”,”deviceNo”:”800xxxxxxxx1234”}
- 这里注意, 路径与body之间是不加点的。
- 这里注意, 路径与body之间是不加点的。
- 这里注意, 路径与body之间是不加点的。
- 如
第二步签名 hex(HmacSHA256(应用id.当前时间戳.post请求的body, 应用密钥appSecret))
- 这里需要转为十六进制小写. 总共64位字符串.
- 示例:
- 假定应用密钥:12345678123456781234567812345678 平台给的 appSecret.
- 算法:hex(HmacSHA256(appId + “.” + timestamp + “.” + path + body, appSecret))
- 得到签名(sign)为:61f5a8f68c2402413d4cd85b98a7d4dd1593184f835c64e1ed50576e8c25705d
第三步拼接授权信息(signInfo) 应用id(appId) 与 当前时间戳(timestamp) 与 签名(sign) 三者用点拼接.
- 如:
- 102.1596794830559.61f5a8f68c2402413d4cd85b98a7d4dd1593184f835c64e1ed50576e8c25705d
- 如:
第四步: 将 以上的授权信息写入 http 请求头 Authorization 中.
- request.setHeader(“Authorization”, signInfo) ;
说明:服务端只有拿到应用才会签名,所以当响应内容 code=200 (见通用响应)才会有签名, 其它状态不一定会有,签名字段也为 Authorization,在响应头中.
签名java代码
package com.test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
/**
* 通用签名小工具.
*
* @author lamb
*/
public final class SignUtil {
/**
* 字符集.
*/
private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8");
/**
* 算法.
*/
private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
/**
* 签名.
*
* @param content 内容.
* @param key key.
* @return 签名.
* @throws Exception 异常.
*/
public static String hmacSha256(String content, String key) throws Exception {
if (null == content || null == key || content.isEmpty() || key.isEmpty()) {
throw new IllegalArgumentException("content or key not found");
}
Mac hmac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET_UTF8), HMAC_SHA256_ALGORITHM);
hmac.init(keySpec);
byte[] array = hmac.doFinal(content.getBytes(CHARSET_UTF8));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
}
return sb.toString().toLowerCase();
}
/**
* 签名小工具.
*
* @param appId 应用id.
* @param appSecret 应用密钥.
* @param timestamp 时间.
* @param body 内容.
* @return 签名, appId.timestamp.signValue.
* @throws Exception e.
*/
public static String sign(String appId, String appSecret, long timestamp,
String path, String body) throws Exception {
if (null == appId || null == appSecret || null == body || null == path) {
throw new IllegalArgumentException("签名失败,签名参数有空值");
}
String auth = appId + "." + timestamp + ".";
auth += hmacSha256(auth + path + body, appSecret);
return auth;
}
}
最后编辑: lamb 文档更新时间: 2022-01-21 17:52 作者:vincent