Functional Weave
Code in Rust

crypto.pbkdf2-sha256@1.0.0

impl/typescript.ts

7,962 bytes · the TypeScript implementation · view raw

// PBKDF2 calls HMAC-SHA256 once per iteration, so a login at 600,000
// iterations is 1.2 million SHA-256 compressions. Two things make that
// affordable in pure code: the key's inner and outer pad blocks are the same
// every time, so their compressed states are computed once and reused (half
// the work of calling HMAC naively), and each iteration hashes a 32-byte
// value that fits one block, so the loop runs on fixed Int32Arrays with no
// allocation. That needs SHA-256's compression function itself, which the
// crypto.sha256 capability does not expose, so it is written out here.

/** FIPS 180-4 section 4.2.2. */
const K = new Int32Array([
  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,
]);

const H0 = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];

const W = new Int32Array(64);

/** One SHA-256 compression of the 16 words in `block` into `state`, in place. */
function compress(state: Int32Array, block: Int32Array): void {
  const w = W;
  for (let t = 0; t < 16; t++) w[t] = block[t];
  for (let t = 16; t < 64; t++) {
    const x = w[t - 15];
    const y = w[t - 2];
    const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
    const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
    w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0;
  }
  let a = state[0], b = state[1], c = state[2], d = state[3], e = state[4], f = state[5], g = state[6], h = state[7];
  for (let t = 0; t < 64; t++) {
    const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
    const t1 = (h + S1 + ((e & f) ^ (~e & g)) + K[t] + w[t]) | 0;
    const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
    const t2 = (S0 + ((a & b) ^ (a & c) ^ (b & c))) | 0;
    h = g;
    g = f;
    f = e;
    e = (d + t1) | 0;
    d = c;
    c = b;
    b = a;
    a = (t1 + t2) | 0;
  }
  state[0] = (state[0] + a) | 0;
  state[1] = (state[1] + b) | 0;
  state[2] = (state[2] + c) | 0;
  state[3] = (state[3] + d) | 0;
  state[4] = (state[4] + e) | 0;
  state[5] = (state[5] + f) | 0;
  state[6] = (state[6] + g) | 0;
  state[7] = (state[7] + h) | 0;
}

/** SHA-256 of a whole byte string, continuing from `state` after `prefixBlocks` blocks already absorbed. */
function hashFrom(state: Int32Array, prefixBlocks: number, bytes: Uint8Array): Int32Array {
  const s = new Int32Array(state);
  const length = prefixBlocks * 64 + bytes.length;
  const blocks = Math.floor((bytes.length + 8) / 64) + 1;
  const padded = new Uint8Array(blocks * 64);
  padded.set(bytes);
  padded[bytes.length] = 0x80;
  const bitsHigh = Math.floor(length / 0x20000000);
  const bitsLow = (length * 8) >>> 0;
  const end = padded.length;
  padded[end - 8] = bitsHigh >>> 24;
  padded[end - 7] = (bitsHigh >>> 16) & 255;
  padded[end - 6] = (bitsHigh >>> 8) & 255;
  padded[end - 5] = bitsHigh & 255;
  padded[end - 4] = bitsLow >>> 24;
  padded[end - 3] = (bitsLow >>> 16) & 255;
  padded[end - 2] = (bitsLow >>> 8) & 255;
  padded[end - 1] = bitsLow & 255;
  const block = new Int32Array(16);
  for (let i = 0; i < blocks; i++) {
    for (let t = 0; t < 16; t++) {
      const j = i * 64 + t * 4;
      block[t] = (padded[j] << 24) | (padded[j + 1] << 16) | (padded[j + 2] << 8) | padded[j + 3];
    }
    compress(s, block);
  }
  return s;
}

function toBytes(value: readonly number[], name: string): Uint8Array {
  if (!Array.isArray(value) && !(value instanceof Uint8Array)) {
    throw new TypeError(`${name} must be a list of integers from 0 to 255`);
  }
  const out = new Uint8Array(value.length);
  for (let i = 0; i < value.length; i++) {
    const b = value[i];
    if (typeof b !== "number" || !Number.isInteger(b) || b < 0 || b > 255) {
      throw new RangeError(`${name} must be a list of integers from 0 to 255`);
    }
    out[i] = b;
  }
  return out;
}

/**
 * PBKDF2-HMAC-SHA256 (RFC 8018 section 5.2): for each 32-byte block i of the
 * key, U1 = HMAC(P, S || INT(i)), Uj = HMAC(P, Uj-1), and the block is the
 * XOR of U1..Uc.
 */
export function pbkdf2Sha256(password: readonly number[], salt: readonly number[], iterations: number, keyLength: number): readonly number[] {
  let key = toBytes(password, "password");
  const saltBytes = toBytes(salt, "salt");
  if (typeof iterations !== "number" || !Number.isInteger(iterations) || iterations < 1) {
    throw new RangeError("iterations must be a whole number of at least 1");
  }
  if (typeof keyLength !== "number" || !Number.isInteger(keyLength) || keyLength < 1) {
    throw new RangeError("keyLength must be a whole number of at least 1");
  }

  // HMAC key preparation (RFC 2104): a key longer than a block is hashed.
  if (key.length > 64) {
    const digest = hashFrom(new Int32Array(H0), 0, key);
    key = new Uint8Array(32);
    for (let i = 0; i < 8; i++) {
      key[i * 4] = digest[i] >>> 24;
      key[i * 4 + 1] = (digest[i] >>> 16) & 255;
      key[i * 4 + 2] = (digest[i] >>> 8) & 255;
      key[i * 4 + 3] = digest[i] & 255;
    }
  }
  const padBlock = new Int32Array(16);
  const innerState = new Int32Array(H0);
  const outerState = new Int32Array(H0);
  for (let t = 0; t < 16; t++) {
    let word = 0;
    for (let k = 0; k < 4; k++) {
      const i = t * 4 + k;
      word = (word << 8) | ((i < key.length ? key[i] : 0) ^ 0x36);
    }
    padBlock[t] = word;
  }
  compress(innerState, padBlock);
  for (let t = 0; t < 16; t++) padBlock[t] ^= 0x36363636 ^ 0x5c5c5c5c;
  compress(outerState, padBlock);

  // A 32-byte message after a 64-byte pad block is one padded block: the
  // digest words, 0x80, zeros and the length, 96 bytes = 768 bits.
  const msg = new Int32Array(16);
  msg[8] = 0x80000000 | 0;
  msg[15] = 768;
  const state = new Int32Array(8);
  const u = new Int32Array(8);
  const acc = new Int32Array(8);

  const out: number[] = [];
  const blocks = Math.ceil(keyLength / 32);
  for (let blockIndex = 1; blockIndex <= blocks; blockIndex++) {
    // U1 = HMAC(P, S || INT(i)), through the general path since the salt can be any length.
    const first = new Uint8Array(saltBytes.length + 4);
    first.set(saltBytes);
    first[saltBytes.length] = blockIndex >>> 24;
    first[saltBytes.length + 1] = (blockIndex >>> 16) & 255;
    first[saltBytes.length + 2] = (blockIndex >>> 8) & 255;
    first[saltBytes.length + 3] = blockIndex & 255;
    const innerDigest = hashFrom(innerState, 1, first);
    for (let t = 0; t < 8; t++) msg[t] = innerDigest[t];
    state.set(outerState);
    compress(state, msg);
    u.set(state);
    acc.set(state);

    for (let j = 1; j < iterations; j++) {
      for (let t = 0; t < 8; t++) msg[t] = u[t];
      state.set(innerState);
      compress(state, msg);
      for (let t = 0; t < 8; t++) msg[t] = state[t];
      state.set(outerState);
      compress(state, msg);
      for (let t = 0; t < 8; t++) {
        u[t] = state[t];
        acc[t] ^= state[t];
      }
    }
    for (let t = 0; t < 8 && out.length < keyLength; t++) {
      const word = acc[t];
      const bytes = [word >>> 24, (word >>> 16) & 255, (word >>> 8) & 255, word & 255];
      for (let k = 0; k < 4 && out.length < keyLength; k++) out.push(bytes[k]);
    }
  }
  return out;
}