-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsalting-and-hashing.ts
34 lines (25 loc) · 1019 Bytes
/
salting-and-hashing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
type User = { email: string; password: string };
const users: User[] = [];
function signup(email: string, password: string) {
const salt = randomBytes(16).toString("hex");
const hashedPassword = scryptSync(password, salt, 64).toString("hex");
const user = { email, password: `${salt}:${hashedPassword}` };
users.push(user);
return user;
}
function login(email: string, password: string) {
const user = users.find(v => v.email === email)!;
const [salt, key] = user.password.split(":");
const hashedBuffer = scryptSync(password, salt, 64);
const keyBuffer = Buffer.from(key, "hex");
const match = timingSafeEqual(hashedBuffer, keyBuffer);
if (match) return "login success";
return "login fail";
}
const user = signup("a@b.com", "abc1234");
console.log({ user });
const wrongCreds = login("a@b.com", "abc123");
console.log({ wrongCreds });
const rightCreds = login("a@b.com", "abc1234");
console.log({ rightCreds });