crypto.ts 7.31 KB
/**
 * 摘要 / MAC 算法 helper。零运行时依赖:MD5 是自带纯实现,HMAC-SHA256 走 Web Crypto。
 *
 * 之所以放在 api-core 而不是各域:签名算法是「接入适配」的公共基建,且 web 子应用与原生
 * 小程序都要用。Web Crypto 在现代浏览器 / Node 18+ / 较高版本微信基础库都可用;若某环境
 * 确实没有 crypto.subtle(极少数老基础库),可改用 createSigner 注入自己的同步算法
 * (例如在 mp 侧引 crypto-js 实现一个 `(msg, secret) => sign` 喂进去)。
 */

/**
 * MD5(RFC 1321)。
 *
 * 老系统的 RPC 网关用 MD5 加签,而这里不引第三方包:catalog 里只有 RSA 链路用到 jsrsasign,
 * 为一个摘要算法再加一份依赖不值当。实现按 32 位有符号整数走,输出小端 16 进制,
 * 已用 RFC 1321 的测试向量核对。
 */
const SHIFT = [
  7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14,
  20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6,
  10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
];

const K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32));

function toUtf8Bytes(input: string): number[] {
  const bytes: number[] = [];
  for (let i = 0; i < input.length; i += 1) {
    let code = input.charCodeAt(i);
    if (code < 0x80) {
      bytes.push(code);
    } else if (code < 0x800) {
      bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f));
    } else if (code < 0xd800 || code >= 0xe000) {
      bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
    } else {
      i += 1;
      code = 0x10000 + (((code & 0x3ff) << 10) | (input.charCodeAt(i) & 0x3ff));
      bytes.push(
        0xf0 | (code >> 18),
        0x80 | ((code >> 12) & 0x3f),
        0x80 | ((code >> 6) & 0x3f),
        0x80 | (code & 0x3f),
      );
    }
  }
  return bytes;
}

function rotateLeft(value: number, amount: number): number {
  return (value << amount) | (value >>> (32 - amount));
}

function hexLittleEndian(word: number): string {
  let out = '';
  for (let i = 0; i < 4; i += 1) {
    out += ((word >>> (i * 8)) & 0xff).toString(16).padStart(2, '0');
  }
  return out;
}

export function md5(input: string): string {
  const message = toUtf8Bytes(input);
  const bitLength = message.length * 8;

  message.push(0x80);
  while (message.length % 64 !== 56) message.push(0);
  message.push(
    bitLength & 0xff,
    (bitLength >>> 8) & 0xff,
    (bitLength >>> 16) & 0xff,
    (bitLength >>> 24) & 0xff,
  );
  message.push(
    Math.floor(bitLength / 2 ** 32) & 0xff,
    Math.floor(bitLength / 2 ** 40) & 0xff,
    Math.floor(bitLength / 2 ** 48) & 0xff,
    Math.floor(bitLength / 2 ** 56) & 0xff,
  );

  let a = 0x67452301;
  let b = 0xefcdab89;
  let c = 0x98badcfe;
  let d = 0x10325476;

  for (let offset = 0; offset < message.length; offset += 64) {
    const words: number[] = [];
    for (let i = 0; i < 16; i += 1) {
      const p = offset + i * 4;
      words.push(
        (message[p]! |
          (message[p + 1]! << 8) |
          (message[p + 2]! << 16) |
          (message[p + 3]! << 24)) >>>
          0,
      );
    }

    let A = a;
    let B = b;
    let C = c;
    let D = d;

    for (let i = 0; i < 64; i += 1) {
      let F: number;
      let g: number;
      if (i < 16) {
        F = (B & C) | (~B & D);
        g = i;
      } else if (i < 32) {
        F = (D & B) | (~D & C);
        g = (5 * i + 1) % 16;
      } else if (i < 48) {
        F = B ^ C ^ D;
        g = (3 * i + 5) % 16;
      } else {
        F = C ^ (B | ~D);
        g = (7 * i) % 16;
      }
      F = (F + A + K[i]! + words[g]!) | 0;
      A = D;
      D = C;
      C = B;
      B = (B + rotateLeft(F, SHIFT[i]!)) | 0;
    }

    a = (a + A) | 0;
    b = (b + B) | 0;
    c = (c + C) | 0;
    d = (d + D) | 0;
  }

  return hexLittleEndian(a) + hexLittleEndian(b) + hexLittleEndian(c) + hexLittleEndian(d);
}

/**
 * HMAC-SHA256(Web Crypto,异步)。返回 64 位小写 hex。
 * 异步是为了不引入 crypto-js 这类同步重依赖;调用方(dispatcher)已对签名做了 await。
 */
export async function hmacSha256(message: string, secret: string): Promise<string> {
  const subtle = globalThis.crypto?.subtle;
  if (!subtle) {
    throw new Error(
      'hmacSha256: 当前环境无 crypto.subtle(老版小程序基础库?),请改用 createSigner 注入同步算法(如 crypto-js)。',
    );
  }
  const enc = new TextEncoder();
  const key = await subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  const signature = await subtle.sign('HMAC', key, enc.encode(message));
  return Array.from(new Uint8Array(signature))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');
}

/**
 * SHA1(RFC 3174)。
 *
 * 原生小程序(points-mall / store-assistant / business-assistant / scrm-carlife)的 RPC 网关
 * 走 SHA1 加签(`sha1(secret + 拼接原文 + secret).toUpperCase()`),与 web points 子应用的
 * MD5 网关是**两套不同算法**——同一网关家族、不同端用不同摘要。为不让 mp 重新造轮子,这里
 * 提供零依赖纯实现,与 MD5 共用 `toUtf8Bytes`,并已用 RFC 3174 测试向量核对。
 */
function leftRotate32(value: number, amount: number): number {
  return ((value << amount) | (value >>> (32 - amount))) >>> 0;
}

function toHexBigEndian(word: number): string {
  return (word >>> 0).toString(16).padStart(8, '0');
}

export function sha1(input: string): string {
  const bytes = toUtf8Bytes(input);
  const bitLen = bytes.length * 8;
  bytes.push(0x80);
  while (bytes.length % 64 !== 56) bytes.push(0);
  // 64 位大端长度;本场景 message 远小于 2^32 位,高 32 位恒为 0。
  const hi = Math.floor(bitLen / 2 ** 32);
  const lo = bitLen >>> 0;
  bytes.push(
    (hi >>> 24) & 0xff,
    (hi >>> 16) & 0xff,
    (hi >>> 8) & 0xff,
    hi & 0xff,
    (lo >>> 24) & 0xff,
    (lo >>> 16) & 0xff,
    (lo >>> 8) & 0xff,
    lo & 0xff,
  );

  let h0 = 0x67452301;
  let h1 = 0xefcdab89;
  let h2 = 0x98badcfe;
  let h3 = 0x10325476;
  let h4 = 0xc3d2e1f0;

  const w = new Array<number>(80);
  for (let i = 0; i < bytes.length; i += 64) {
    for (let j = 0; j < 16; j += 1) {
      const p = i + j * 4;
      w[j] =
        ((bytes[p]! << 24) |
          (bytes[p + 1]! << 16) |
          (bytes[p + 2]! << 8) |
          bytes[p + 3]!) >>>
        0;
    }
    for (let j = 16; j < 80; j += 1) {
      w[j] = leftRotate32(w[j - 3]! ^ w[j - 8]! ^ w[j - 14]! ^ w[j - 16]!, 1);
    }
    let a = h0;
    let b = h1;
    let c = h2;
    let d = h3;
    let e = h4;
    for (let j = 0; j < 80; j += 1) {
      let f: number;
      let k: number;
      if (j < 20) {
        f = (b & c) | (~b & d);
        k = 0x5a827999;
      } else if (j < 40) {
        f = b ^ c ^ d;
        k = 0x6ed9eba1;
      } else if (j < 60) {
        f = (b & c) | (b & d) | (c & d);
        k = 0x8f1bbcdc;
      } else {
        f = b ^ c ^ d;
        k = 0xca62c1d6;
      }
      const temp = (leftRotate32(a, 5) + f + e + k + w[j]!) | 0;
      e = d;
      d = c;
      c = leftRotate32(b, 30);
      b = a;
      a = temp >>> 0;
    }
    h0 = (h0 + a) | 0;
    h1 = (h1 + b) | 0;
    h2 = (h2 + c) | 0;
    h3 = (h3 + d) | 0;
    h4 = (h4 + e) | 0;
  }

  return [h0, h1, h2, h3, h4].map(toHexBigEndian).join('');
}