forked from mtusi2026/mtusi2026lab2
20 lines
909 B
TypeScript
20 lines
909 B
TypeScript
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
|
|
import { promisify } from 'node:util';
|
|
|
|
const derive = promisify(scrypt);
|
|
const dummyHash = 'scrypt$00000000000000000000000000000000$' + '0'.repeat(128);
|
|
|
|
export async function hashPassword(password: string): Promise<string> {
|
|
const salt = randomBytes(16);
|
|
const key = (await derive(password, salt, 64)) as Buffer;
|
|
return `scrypt$${salt.toString('hex')}$${key.toString('hex')}`;
|
|
}
|
|
|
|
export async function verifyPassword(password: string, stored: string | undefined): Promise<boolean> {
|
|
const [, salt, hash] = (stored ?? dummyHash).split('$');
|
|
if (!salt || !hash) throw new Error('Invalid password hash');
|
|
const expected = Buffer.from(hash, 'hex');
|
|
const actual = (await derive(password, Buffer.from(salt, 'hex'), expected.length)) as Buffer;
|
|
return timingSafeEqual(actual, expected) && stored !== undefined;
|
|
}
|