crypto.ts 11.5 KB
/**
 * 摘要 / MAC 算法 helper。零运行时依赖:MD5 / SHA1 / SHA256 都是纯实现,HMAC 有 Web Crypto
 * (异步)与纯实现(同步)两条路。
 *
 * 之所以放在 api-core 而不是各域:签名算法是「接入适配」的公共基建,且 web 子应用与原生
 * 小程序都要用。Web Crypto 在现代浏览器 / Node 18+ 可用,但原生小程序没有 crypto.subtle,
 * 因此 HMAC 另提供 hmacSha256Sync,签名器可按运行环境选择。
 */

/**
 * MD5(RFC 1321)。
 *
 * 部分老链路用 MD5 加签(注意:glsx 系 RPC 网关实际是 SHA1,见 signers.ts),这里不引第三方包:
 * 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)与 web points
 * 子应用的 glsx RPC 网关**都走 SHA1 加签**(`sha1(secret + 拼接原文 + secret).toUpperCase()`),
 * 差别只在 web 侧 timestamp 也进签名原文。为不让 mp 重新造轮子,这里提供零依赖纯实现,
 * 与 MD5 共用 `toUtf8Bytes`,并已用 RFC 3174 测试向量及真实抓包 golden 值核对。
 */
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('');
}

/**
 * SHA-256(FIPS 180-4)。GSC 网关的头部签名走 HMAC-SHA256,而原生小程序没有 Web Crypto,
 * 故提供纯实现;与 MD5 / SHA1 共用 `toUtf8Bytes`,已用 NIST 向量核对。
 */
const SHA256_K = [
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];

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

function sha256Bytes(message: number[]): number[] {
  const bytes = message.slice();
  const bitLen = bytes.length * 8;
  bytes.push(0x80);
  while (bytes.length % 64 !== 56) bytes.push(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 = 0x6a09e667;
  let h1 = 0xbb67ae85;
  let h2 = 0x3c6ef372;
  let h3 = 0xa54ff53a;
  let h4 = 0x510e527f;
  let h5 = 0x9b05688c;
  let h6 = 0x1f83d9ab;
  let h7 = 0x5be0cd19;

  const w = new Array<number>(64);
  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 < 64; j += 1) {
      const x = w[j - 15]!;
      const y = w[j - 2]!;
      const s0 = rotateRight(x, 7) ^ rotateRight(x, 18) ^ (x >>> 3);
      const s1 = rotateRight(y, 17) ^ rotateRight(y, 19) ^ (y >>> 10);
      w[j] = (w[j - 16]! + s0 + w[j - 7]! + s1) >>> 0;
    }
    let a = h0;
    let b = h1;
    let c = h2;
    let d = h3;
    let e = h4;
    let f = h5;
    let g = h6;
    let h = h7;
    for (let j = 0; j < 64; j += 1) {
      const S1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
      const ch = (e & f) ^ (~e & g);
      const temp1 = (h + S1 + ch + SHA256_K[j]! + w[j]!) | 0;
      const S0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
      const maj = (a & b) ^ (a & c) ^ (b & c);
      const temp2 = (S0 + maj) | 0;
      h = g;
      g = f;
      f = e;
      e = (d + temp1) | 0;
      d = c;
      c = b;
      b = a;
      a = (temp1 + temp2) | 0;
    }
    h0 = (h0 + a) | 0;
    h1 = (h1 + b) | 0;
    h2 = (h2 + c) | 0;
    h3 = (h3 + d) | 0;
    h4 = (h4 + e) | 0;
    h5 = (h5 + f) | 0;
    h6 = (h6 + g) | 0;
    h7 = (h7 + h) | 0;
  }

  const hash = [h0, h1, h2, h3, h4, h5, h6, h7];
  const digest: number[] = [];
  for (let i = 0; i < hash.length; i += 1) {
    const word = hash[i]!;
    digest.push((word >>> 24) & 0xff, (word >>> 16) & 0xff, (word >>> 8) & 0xff, word & 0xff);
  }
  return digest;
}

export function sha256(input: string): string {
  return sha256Bytes(toUtf8Bytes(input))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');
}

/**
 * HMAC-SHA256(同步纯实现,RFC 2104)。返回 64 位小写 hex,与 crypto-js
 * `HmacSHA256(msg, key).toString()` 一致;原生小程序用这个,web / Node 可用上面的异步版。
 */
export function hmacSha256Sync(message: string, secret: string): string {
  const blockSize = 64;
  let key = toUtf8Bytes(secret);
  if (key.length > blockSize) key = sha256Bytes(key);
  while (key.length < blockSize) key.push(0);

  const inner = key.map((b) => b ^ 0x36).concat(toUtf8Bytes(message));
  const outer = key.map((b) => b ^ 0x5c).concat(sha256Bytes(inner));
  return sha256Bytes(outer)
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');
}