32 lines
1.0 KiB
JavaScript
32 lines
1.0 KiB
JavaScript
/**
|
|
* HMAC-SHA256 签名工具
|
|
*
|
|
* 签名规则:
|
|
* 1. 将 GET 的 Query 参数 + nonce + timestamp 按 key 字母序排列
|
|
* 2. 格式: key1=value1&key2=value2&...
|
|
* 3. POST/PUT 的 JSON body 不参与签名
|
|
* 4. 使用 HMAC-SHA256 算法,以 appSecret 为密钥,输出 hex 小写
|
|
*/
|
|
|
|
import CryptoJS from 'crypto-js'
|
|
|
|
export function generateSignHeaders(appKey, appSecret, queryParams = {}) {
|
|
const timestamp = Date.now().toString()
|
|
const nonce = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
|
|
|
|
// Build signature string: sorted query params + nonce + timestamp
|
|
const signParams = { ...queryParams, nonce, timestamp }
|
|
const sortedKeys = Object.keys(signParams).sort()
|
|
const signString = sortedKeys.map(k => `${k}=${signParams[k]}`).join('&')
|
|
|
|
// HMAC-SHA256
|
|
const signature = CryptoJS.HmacSHA256(signString, appSecret).toString(CryptoJS.enc.Hex)
|
|
|
|
return {
|
|
'X-App-Key': appKey,
|
|
'X-Timestamp': timestamp,
|
|
'X-Nonce': nonce,
|
|
'X-Signature': signature
|
|
}
|
|
}
|