crypto.ts 4.77 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('');
}