forked from codechefPesuecc/CodeChef-PESUECC-Chapter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpassword.ts
More file actions
23 lines (20 loc) · 780 Bytes
/
Copy pathpassword.ts
File metadata and controls
23 lines (20 loc) · 780 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import crypto from "node:crypto";
/**
* Password hashing with Node's built-in scrypt — no third-party dependency.
* Stored as `salt:hash` (both hex). Verification is constant-time.
*/
const KEYLEN = 64;
export function hashPassword(password: string): string {
const salt = crypto.randomBytes(16).toString("hex");
const hash = crypto.scryptSync(password, salt, KEYLEN).toString("hex");
return `${salt}:${hash}`;
}
export function verifyPassword(password: string, stored: string): boolean {
const [salt, hash] = stored.split(":");
if (!salt || !hash) return false;
const test = crypto.scryptSync(password, salt, KEYLEN);
const expected = Buffer.from(hash, "hex");
return (
expected.length === test.length && crypto.timingSafeEqual(expected, test)
);
}