const iterations = 210_000; function encode(bytes: Uint8Array) { return Buffer.from(bytes).toString("base64url"); } async function derive(password: string, salt: Uint8Array, rounds = iterations) { const saltBuffer = salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength) as ArrayBuffer; const key = await crypto.subtle.importKey( "raw", new TextEncoder().encode(password), "PBKDF2", false, ["deriveBits"], ); return new Uint8Array(await crypto.subtle.deriveBits( { name: "PBKDF2", salt: saltBuffer, iterations: rounds, hash: "SHA-256" }, key, 256, )); } export function validPassword(value: unknown) { return typeof value === "string" && value.length >= 8 && value.length <= 128; } export async function hashPassword(password: string) { const salt = crypto.getRandomValues(new Uint8Array(16)); return `pbkdf2_sha256$${iterations}$${encode(salt)}$${encode(await derive(password, salt))}`; } export async function verifyPassword(password: string, stored: string) { const [algorithm, roundsValue, saltValue, expected] = stored.split("$"); const rounds = Number(roundsValue); if (algorithm !== "pbkdf2_sha256" || !saltValue || !expected || rounds < 100_000) return false; const actual = encode(await derive(password, Buffer.from(saltValue, "base64url"), rounds)); if (actual.length !== expected.length) return false; let mismatch = 0; for (let index = 0; index < actual.length; index += 1) { mismatch |= actual.charCodeAt(index) ^ expected.charCodeAt(index); } return mismatch === 0; }