Open in a new tab

Derive a password hash with Argon2id (the WASM tier) or PBKDF2-HMAC-SHA256 (pure JavaScript), keep the parameters and salt with the hash, and verify a password against that record.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Passwords must never be stored or compared in clear. Argon2id is the current recommendation; PBKDF2 is the portable fallback when WebAssembly is off. The record format here (algorithm, salt, params, hash) lets you raise the parameters later without breaking old records.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The .wasm file loads from /vendor/fw/crypto/wasm/. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Keep ARGON2_PARAMS at an OWASP configuration (12 MiB / 3 passes here; the bundled WASM module serves up to 12 MiB) and the PBKDF2 count at 600 000 or above; hash on the server too if the password leaves the page.

What it shows

  • wasmArgon2.isAvailable(), then hash(passwordBytes, salt, { timeCost, memoryKiB, parallelism, hashLen }) and verify(...) (async, WASM).
  • pbkdf2(password, saltBits, iterations, bits) with bitArray.equal for a constant-time compare, and a public PBKDF2-HMAC-SHA256 known answer.
  • random.bytes(16) for a fresh salt per hash: two hashes of one password never match.

Code

main.js

javascriptApache-2.079 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { wasmArgon2 } from '@awacloud/fw/crypto/wasm/argon2.js';
import { pbkdf2 } from '@awacloud/fw/crypto/hash/pbkdf2.js';
import { random } from '@awacloud/fw/crypto/utils/random.js';
import { hex } from '@awacloud/fw/io/codec/hex.js';

fw.runtime.registerAllDeep([wasmArgon2, pbkdf2, random, hex]);
const ARGON2 = fw.runtime.resolve('wasmArgon2');
const PBKDF2 = fw.runtime.resolve('pbkdf2');
const RANDOM = fw.runtime.resolve('random');
const BA = fw.runtime.resolve('bitArray');

/** Argon2id: one of OWASP's recommended configurations (12 MiB, 3 passes). */
export const ARGON2_PARAMS = { timeCost: 3, memoryKiB: 12 * 1024, parallelism: 1, hashLen: 32 };
/** PBKDF2-HMAC-SHA256 iteration count (OWASP 2023) and output size in bits. */
export const PBKDF2_PARAMS = { iterations: 600000, bits: 256 };
const encoder = new TextEncoder();
const HEX = fw.runtime.resolve('hex');

/**
 * @typedef {{ algorithm: 'argon2id' | 'pbkdf2-sha256', salt: string, params: object, hash: string }} StoredHash
 */

/**
 * Argon2id when WebAssembly is available, PBKDF2 otherwise: the record says
 * which, with its parameters and salt, so verification never guesses.
 * @param {string} password
 * @param {{ argon2?: typeof ARGON2_PARAMS, pbkdf2?: typeof PBKDF2_PARAMS }} [params]
 * @returns {Promise<StoredHash>}
 */
export async function hashPassword(password, params = {}) {
    const salt = /** @type {Uint8Array} */ (RANDOM.bytes(16));
    /** @type {(algorithm: StoredHash['algorithm'], used: object, hash: Uint8Array) => StoredHash} */
    const record = (algorithm, used, hash) => (
        { algorithm, salt: HEX.fromBytes(salt), params: used, hash: HEX.fromBytes(hash) });
    const argon2 = params.argon2 ?? ARGON2_PARAMS;
    const digest = ARGON2.isAvailable() ? await ARGON2.hash(encoder.encode(password), salt, argon2) : null;
    if (digest) return record('argon2id', argon2, digest);
    const p = params.pbkdf2 ?? PBKDF2_PARAMS;
    return record('pbkdf2-sha256', p, BA.ba_to_ui8(PBKDF2(password, BA.ui8_to_ba(salt), p.iterations, p.bits)));
}

/**
 * @param {string} password
 * @param {StoredHash} stored
 * @returns {Promise<boolean>}
 */
export async function verifyPassword(password, stored) {
    const salt = HEX.toBytes(stored.salt);
    if (stored.algorithm === 'argon2id') {
        const params = /** @type {typeof ARGON2_PARAMS} */ (stored.params);
        return ARGON2.verify(encoder.encode(password), salt, HEX.toBytes(stored.hash), params);
    }
    const p = /** @type {typeof PBKDF2_PARAMS} */ (stored.params);
    const digest = /** @type {number[]} */ (PBKDF2(password, BA.ui8_to_ba(salt), p.iterations, p.bits));
    return BA.equal(digest, BA.ui8_to_ba(HEX.toBytes(stored.hash)));
}

/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };
/** @param {string} id */
const field = (id) => /** @type {HTMLInputElement} */ (document.getElementById(id));
/** @type {StoredHash | null} */
let stored = null;

/** @type {HTMLElement} */ (document.getElementById('hash')).addEventListener('click', async () => {
    show('status', 'hashing…');
    // The hash blocks the main thread: let the status paint first (one frame).
    await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve)));
    stored = await hashPassword(field('password').value);
    const tier = stored.algorithm === 'argon2id' ? 'argon2id (WASM tier)' : 'pbkdf2-sha256 (pure JavaScript fallback)';
    show('status', tier);
    show('record', JSON.stringify(stored, null, 2));
});
/** @type {HTMLElement} */ (document.getElementById('verify')).addEventListener('click', async () => {
    if (!stored) return show('verdict', 'hash a password first');
    show('verdict', (await verifyPassword(field('attempt').value, stored)) ? 'password accepted' : 'password rejected');
});

index.html

htmlApache-2.029 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Hash a password with Argon2id or PBKDF2</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Hash a password with Argon2id or PBKDF2</h1>
    <label for="password">Password to store</label>
    <input id="password" type="password" value="correct horse battery staple" autocomplete="new-password">
    <button id="hash" type="button">Hash it</button>
    <p id="status" aria-live="polite"></p>
    <pre id="record" aria-label="Stored record"></pre>
    <label for="attempt">Password to verify</label>
    <input id="attempt" type="password" value="correct horse battery staple" autocomplete="off">
    <button id="verify" type="button">Verify</button>
    <p id="verdict" aria-live="polite"></p>
  </main>
</body>
</html>