File size: 1,188 Bytes
9d4a3b0 | 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 | import { pbkdf2 as pbkdf2Callback, randomBytes, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
const pbkdf2 = promisify(pbkdf2Callback);
const iterations = 310_000;
export function validatePassword(password: string) {
return password.length >= 10 && /[a-z]/.test(password) && /[A-Z]/.test(password) && /\d/.test(password);
}
export async function hashPassword(password: string) {
const salt = randomBytes(16);
const hash = await pbkdf2(password, salt, iterations, 32, "sha256");
return `pbkdf2_sha256$${iterations}$${salt.toString("base64url")}$${hash.toString("base64url")}`;
}
export async function verifyPassword(password: string, stored: string) {
const [algorithm, roundsValue, saltValue, hashValue] = stored.split("$");
const rounds = Number(roundsValue);
if (algorithm !== "pbkdf2_sha256" || !Number.isInteger(rounds) || rounds < 100_000 || !saltValue || !hashValue) return false;
const expected = Buffer.from(hashValue, "base64url");
const actual = await pbkdf2(password, Buffer.from(saltValue, "base64url"), rounds, expected.length, "sha256");
return expected.length === actual.length && timingSafeEqual(expected, actual);
}
|