跳转至

A 模式签名规则(md5-timestamp-rand)

概述

A 模式是基于 MD5 哈希算法的鉴权方式,通过时间戳和随机字符串确保签名的唯一性和时效性。

签名格式

A 模式的签名格式如下:

signature = md5hex + "-" + timestamp + "-" + rand

参数说明

参数 说明
md5hex 明文的 MD5 值(32 位小写),md5hex = md5(uri-timestamp-rand-secret)。
timestamp 秒级 Unix 时间戳(整数)。
rand 随机字符串(建议长度为 8~32 位)。

请求示例

GET /api/order/list HTTP/1.1
Host: example.com
signature: 5d41402abc4b2a76b9719d911017c592-1694502400-8271SLDF

JavaScript 实现示例

/**
 * 生成 A 模式 signature
 * @param {string} uri 请求路径,例如 "/api/order/list"
 * @param {string} secret 鉴权密钥
 * @returns {Promise<string>} 生成的签名字符串
 */
async function generateSignatureTypeA(uri, secret) {
  // 1. 获取当前秒级时间戳
  const timestamp = Math.floor(Date.now() / 1000);

  // 2. 生成 12 位随机字符串
  const rand = randomString(12);

  // 3. 按照规则拼接明文
  const plaintext = `${uri}-${timestamp}-${rand}-${secret}`;

  // 4. 计算明文的 MD5 值(32 位小写)
  const md5hex = await md5Hex(plaintext);

  // 5. 组合生成最终的 signature
  return `${md5hex}-${timestamp}-${rand}`;
}

/**
 * 生成指定长度的随机字符串
 * @param {number} length 字符串长度,默认 12
 * @returns {string} 随机字符串
 */
function randomString(length = 12) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const bytes = new Uint8Array(length);
  crypto.getRandomValues(bytes);
  let out = "";
  for (let i = 0; i < length; i++) {
    out += chars[bytes[i] % chars.length];
  }
  return out;
}

/**
 * MD5 哈希函数实现
 * @param {string} input 输入字符串
 * @returns {Promise<string>} MD5 哈希值(32 位小写)
 * @note 请替换为项目中实际使用的 MD5 实现,例如 crypto-js、blueimp-md5 等库
 */
async function md5Hex(input) {
  return md5(input).toLowerCase(); 
}