forked from mtusi2026/mtusi2026lab2
[+] Completed lab 2
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user