动态鉴权签名生成规则
更新时间:2026-07-15
签名只对以下字段进⾏计算,不包含 signature 本身,不包含 apptoken 明⽂,也不包含业务参数 data。
- appid
- timestamp
- nonce
拼接签名原文
按以下顺序使⽤换⾏符 \n 拼接:
Plain Text
1stringToSign = appid + "\n" + timestamp + "\n" + nonce
生成签名
使⽤ apptoken 作为密钥,对 stringToSign 进⾏ HMAC-SHA256 签名:
Plain Text
1signature = HMAC-SHA256(stringToSign, apptoken)
签名结果使用小写十六进制字符串。
代码参考
Java
1String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
2String nonce = UUID.randomUUID().toString().replace("-", "");
3String signature = hmacSha256Hex(
4 String.join("\n", authInfo.getAppid(), timestamp, nonce),
5 authInfo.getApptoken());
6
7
8public static String hmacSha256Hex(String data, String key) {
9 try {
10 Mac mac = Mac.getInstance("HmacSHA256");
11 mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
12 byte[] bytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
13 StringBuilder sb = new StringBuilder();
14 for (byte b : bytes) {
15 sb.append(String.format("%02x", b));
16 }
17 return sb.toString();
18 } catch (Exception e) {
19 throw new RuntimeException("hmac-sha256 sign failed", e);
20 }
21}
评价此篇文章
