tests/sims/password.test.ts
The automated tests for the /simulators/password-hashing simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.
- SHA-256, salted SHA-256, PBKDF2 and scrypt hashes are byte-for-byte what Python's hashlib computes.
- Bcrypt and Argon2id strings are accepted by the Python bcrypt and argon2-cffi libraries.
- Logging in with the right password succeeds and any other password fails, for every algorithm.
- SHA-256 of "abc" is the FIPS 180-2 test vector.
// /simulators/password-hashing: SHA-256, salted SHA-256, PBKDF2, bcrypt, scrypt and Argon2id.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { hash, verify, toHex, type AlgoId, type Params } from '../../src/lib/sims/passwordHash.ts';
const has = (mod: string) => { try { execFileSync('python3', ['-c', `import ${mod}`], { stdio: 'ignore' }); return true; } catch { return false; } };
const py = has('hashlib'), pyBcrypt = py && has('bcrypt'), pyArgon = py && has('argon2');
const PASSWORDS = ['hunter2', 'correct horse battery staple', 'pässwörd-ünïcode', ''];
const SALT = Uint8Array.from({ length: 16 }, (_, i) => (i * 37 + 11) & 255);
const CASES: [AlgoId, Params][] = [
['sha256', {}], ['sha256salt', {}], ['pbkdf2', { iterations: 1000 }], ['scrypt', { logN: 10, r: 8, p: 1 }],
['bcrypt', { cost: 4 }], ['argon2id', { memKiB: 1024, t: 2, p: 1 }]
];
async function stored() {
const out: { algo: AlgoId; pw: string; stored: string; digest: string }[] = [];
for (const [algo, params] of CASES) for (const pw of PASSWORDS) {
if ((algo === 'bcrypt' || algo === 'argon2id') && pw === '') continue; // hash-wasm refuses these; the page says so
const h = await hash(algo, pw, SALT, params);
out.push({ algo, pw, ...h });
}
return out;
}
test("SHA-256, salted SHA-256, PBKDF2 and scrypt hashes are byte-for-byte what Python's hashlib computes", { skip: !py && 'python3 is not installed' }, async () => {
const rows = (await stored()).filter((r) => ['sha256', 'sha256salt', 'pbkdf2', 'scrypt'].includes(r.algo));
const want = JSON.parse(execFileSync('python3', ['-c', `
import hashlib, json, sys
rows, salt = json.loads(sys.stdin.read())
salt = bytes(salt)
out = []
for r in rows:
pw = r['pw'].encode()
a = r['algo']
if a == 'sha256': d = hashlib.sha256(pw).digest()
elif a == 'sha256salt': d = hashlib.sha256(salt + pw).digest()
elif a == 'pbkdf2': d = hashlib.pbkdf2_hmac('sha256', pw, salt, 1000, 32)
else: d = hashlib.scrypt(pw, salt=salt, n=2**10, r=8, p=1, dklen=32)
out.append(d.hex())
print(json.dumps(out))
`], { input: JSON.stringify([rows, [...SALT]]) }).toString());
rows.forEach((r, i) => assert.equal(r.digest, want[i], `${r.algo} of "${r.pw}"`));
});
test('bcrypt and Argon2id strings are accepted by the Python bcrypt and argon2-cffi libraries', { skip: !(pyBcrypt && pyArgon) && 'python bcrypt or argon2-cffi is not installed' }, async () => {
const rows = (await stored()).filter((r) => r.algo === 'bcrypt' || r.algo === 'argon2id');
const ok = JSON.parse(execFileSync('python3', ['-c', `
import bcrypt, json, sys
from argon2 import PasswordHasher
ph = PasswordHasher()
out = []
for r in json.loads(sys.stdin.read()):
pw = r['pw'].encode()
if r['algo'] == 'bcrypt': out.append(bcrypt.checkpw(pw, r['stored'].encode()) and not bcrypt.checkpw(pw + b'x', r['stored'].encode()))
else:
try: good = ph.verify(r['stored'], pw)
except Exception: good = False
try: ph.verify(r['stored'], pw + b'x'); bad = True
except Exception: bad = False
out.append(good and not bad)
print(json.dumps(out))
`], { input: JSON.stringify(rows) }).toString());
rows.forEach((r, i) => assert.ok(ok[i], `${r.algo} of "${r.pw}": ${r.stored}`));
});
test('logging in with the right password succeeds and any other password fails, for every algorithm', async () => {
for (const r of await stored()) {
assert.equal(await verify(r.stored, r.pw), true, `${r.algo}: right password rejected`);
assert.equal(await verify(r.stored, r.pw + '!'), false, `${r.algo}: wrong password accepted`);
if (r.pw !== '') assert.equal(await verify(r.stored, ''), false, `${r.algo}: empty password accepted`);
}
});
test('SHA-256 of "abc" is the FIPS 180-2 test vector', async () => {
const h = await hash('sha256', 'abc', new Uint8Array(), {});
assert.equal(h.digest, 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
assert.equal(toHex(new Uint8Array([0, 255])), '00ff');
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.