Skip to content

Argon2 Hash & Verify — JavaScript source

Hash passwords with Argon2id — the winner of the Password Hashing Competition. Configure memory, iterations, and parallelism. WASM-powered, client-side.

This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

/**
 * argon2 — Argon2id password hashing (PHC parse/format logic in pure JS; the
 * KDF itself via the reference argon2(1) CLI).
 *
 * Language: JavaScript (ES2022; Node >= 20, Bun, Deno — no top-level imports,
 * no dependencies).
 * CosmoDev polyglot showcase port of the `argon2` tool, ported from
 * src/lib/argon2.ts (the canonical TypeScript implementation).
 *
 * The TS build drives the reference C library compiled to WASM
 * (argon2-browser), but WebCrypto has no Argon2. Like the Ruby / C# / Java /
 * Swift siblings, this port keeps the PHC parser, validator and Base64 codec
 * pure JS and delegates the KDF itself to the same reference C library
 * through its CLI: `argon2` (https://github.com/P-H-C/phc-winner-argon2) must
 * be on PATH for argon2Hash / argon2Verify. The only non-global access is a
 * lazily imported node:child_process, grabbed inside the one helper that
 * spawns the CLI — the rest runs on web-standard globals.
 *
 * The CLI takes its salt as an argv *string*, and argv must be valid UTF-8 —
 * raw random bytes >= 0x80 do not round-trip. Salts are therefore passed (and
 * recorded in the PHC string) as their 32-char lowercase hex rendering:
 * ASCII survives every platform encoding and still carries 128 bits.
 *
 * PHC string format (what `encoded` holds - the string you store in a DB):
 *   $argon2id$v=19$m=65536,t=3,p=1$<b64 salt>$<b64 digest>
 * Salt and digest are unpadded standard Base64.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

/** Defaults follow the OWASP-recommended Argon2id profile (64 MiB, 3 passes). */
export const ARGON2_DEFAULTS = { memory: 65_536, iterations: 3, parallelism: 1, hashLength: 32 };

/** Random salt size in bytes (128 bits - the PHC recommendation). */
export const SALT_BYTES = 16;

/** CLI variant flags, keyed by the type read out of a PHC string. */
const CLI_FLAG = { argon2d: '-d', argon2i: '-i', argon2id: '-id' };

const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const B64_INDEX = Object.fromEntries([...B64_ALPHABET].map((c, i) => [c, i]));

/** Lowercase hex of a byte array. */
function bytesToHex(bytes) {
  return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
}

/** Unpadded standard Base64 (the PHC encoding) -> bytes. Throws on any
 *  non-alphabet character or an impossible length (1 mod 4). */
function phcBase64ToBytes(b64) {
  if (b64.length === 0) throw new Error('Invalid Argon2 string: empty Base64 field');
  if (!/^[A-Za-z0-9+/]+$/.test(b64)) throw new Error('Invalid Argon2 string: non-Base64 characters');
  if (b64.length % 4 === 1) throw new Error('Invalid Argon2 string: impossible Base64 length');
  const out = new Uint8Array(Math.floor((b64.length * 3) / 4));
  let acc = 0, bits = 0, p = 0;
  for (let i = 0; i < b64.length; i++) {
    acc = (acc << 6) | B64_INDEX[b64[i]];
    bits += 6;
    if (bits >= 8) {
      out[p++] = (acc >> (bits - 8)) & 0xff;
      bits -= 8;
    }
  }
  return out;
}

/**
 * Parse a PHC-format Argon2 string (`$argon2id$v=19$m=65536,t=3,p=1$salt$hash`)
 * into its typed parameters. Accepts argon2d / argon2i / argon2id. The digest
 * segment is optional (some encoders omit it); salt and hash are returned as
 * lowercase hex. Throws on any malformed input.
 */
export function parseArgon2(encoded) {
  const m = /^\$(argon2(?:d|i|id))\$v=(\d+)\$m=(\d+),t=(\d+),p=(\d+)\$([A-Za-z0-9+/]+)(?:\$([A-Za-z0-9+/]+))?$/.exec(
    encoded.trim(),
  );
  if (!m) throw new Error('Invalid Argon2 string: expected $argon2id$v=19$m=…,t=…,p=…$salt$hash');
  return {
    type: m[1],
    version: Number(m[2]),
    memory: Number(m[3]),
    iterations: Number(m[4]),
    parallelism: Number(m[5]),
    salt: bytesToHex(phcBase64ToBytes(m[6])),
    hash: m[7] ? bytesToHex(phcBase64ToBytes(m[7])) : '',
  };
}

/** Validate + normalise hashing parameters, throwing with a clear message. */
function normalizeOptions(options) {
  const { memory = ARGON2_DEFAULTS.memory, iterations = ARGON2_DEFAULTS.iterations } = options;
  const { parallelism = ARGON2_DEFAULTS.parallelism, hashLength = ARGON2_DEFAULTS.hashLength } = options;
  if (!Number.isFinite(memory) || memory < 1024) throw new Error('Memory must be at least 1024 KiB');
  if (!Number.isFinite(iterations) || iterations < 1) throw new Error('Iterations must be at least 1');
  if (!Number.isFinite(parallelism) || parallelism < 1) throw new Error('Parallelism must be at least 1');
  if (!Number.isFinite(hashLength) || hashLength < 16 || hashLength > 64) {
    throw new Error('Hash length must be between 16 and 64 bytes');
  }
  return { memory, iterations, parallelism, hashLength };
}

/** Spawn `argon2`, feed `password` on stdin, and resolve its stdout bytes.
 *  Non-zero exit rejects with the CLI's stderr text. node:child_process is
 *  imported lazily so the file itself stays import-free. */
async function runArgon2(args, password) {
  const cp = await import('node:child_process');
  return new Promise((resolve, reject) => {
    const child = cp.execFile('argon2', args, { encoding: 'buffer' }, (error, stdout, stderr) => {
      const message = stderr.toString().trim();
      if (error) reject(new Error(message ? `argon2 failed: ${message}` : `argon2 failed: ${error.message}`));
      else resolve(new Uint8Array(stdout));
    });
    child.stdin.end(password, 'utf8');
  });
}

/**
 * Hash a password with Argon2id (hybrid of Argon2i's side-channel resistance
 * and Argon2d's GPU resistance - the Password Hashing Competition winner and
 * the recommended mode for password storage). Returns the digest (hex), the
 * salt used (hex), and the self-contained PHC string. A fresh random 16-byte
 * salt is generated per call unless `options.salt` (bytes) is given; either
 * way the salt travels to the CLI as its lowercase hex rendering (see the
 * header note), and the returned `salt`/`encoded` describe that exact form.
 */
export async function argon2Hash(password, options = {}) {
  const { memory, iterations, parallelism, hashLength } = normalizeOptions(options);
  const random = new Uint8Array(SALT_BYTES);
  crypto.getRandomValues(random);
  const saltText = options.salt !== undefined ? bytesToHex(options.salt) : bytesToHex(random);
  const encoded = new TextDecoder()
    .decode(
      await runArgon2(
        [saltText, CLI_FLAG.argon2id, '-v', '13', '-e', '-k', String(memory), '-t', String(iterations),
          '-p', String(parallelism), '-l', String(hashLength)],
        password,
      ),
    )
    .trim();
  // The digest is the final PHC segment; read it back so hash/encoded always
  // describe one self-consistent hash.
  const digest = phcBase64ToBytes(encoded.split('$').at(-1));
  return { hash: bytesToHex(digest), encoded, salt: bytesToHex(new TextEncoder().encode(saltText)) };
}

/**
 * Verify a password against a PHC-format encoded hash (as produced by
 * argon2Hash). Resolves true on match, false on mismatch; throws only on a
 * malformed encoded string or a runtime error. Any Argon2 type (d/i/id) is
 * accepted - the type is read from the string itself. The CLI has no verify
 * mode, so this recomputes the hash with the embedded parameters + salt and
 * compares (what the C library's argon2_verify does internally). Recomputing
 * with -e (rather than -r, whose output differs between CLI builds) and
 * comparing PHC segments keeps the comparison exact.
 */
export async function argon2Verify(encoded, password) {
  const params = parseArgon2(encoded); // validate format up front
  const segments = encoded.trim().split('$');
  const saltBytes = phcBase64ToBytes(segments[4]);
  // argv must be valid UTF-8: raw-byte salts (e.g. from the TS/WASM build)
  // cannot round-trip and are rejected here rather than hashed wrongly.
  let saltText;
  try {
    saltText = new TextDecoder('utf-8', { fatal: true }).decode(saltBytes);
  } catch {
    throw new Error('Salt is not ASCII; the argon2 CLI takes its salt as an argv string');
  }
  const hashLength = params.hash ? params.hash.length / 2 : ARGON2_DEFAULTS.hashLength;
  const recomputed = new TextDecoder()
    .decode(
      await runArgon2(
        [saltText, CLI_FLAG[params.type], '-v', '13', '-e', '-k', String(params.memory),
          '-t', String(params.iterations), '-p', String(params.parallelism), '-l', String(hashLength)],
        password,
      ),
    )
    .trim();
  if (params.hash) return recomputed.split('$').at(-1) === segments[5];
  // No embedded digest: compare the freshly re-encoded PHC string as a whole.
  return recomputed === encoded.trim();
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →