haixunMaster/lib/auth/password.ts

18 lines
646 B
TypeScript
Raw Normal View History

2026-06-21 12:50:31 +00:00
import { randomBytes, scryptSync, timingSafeEqual } from "crypto";
const KEY_LEN = 64;
export function hashPassword(password: string): string {
const salt = randomBytes(16).toString("hex");
const hash = scryptSync(password, salt, KEY_LEN).toString("hex");
return `${salt}:${hash}`;
}
export function verifyPassword(password: string, stored: string): boolean {
const [salt, hash] = stored.split(":");
if (!salt || !hash) return false;
const hashBuffer = Buffer.from(hash, "hex");
const test = scryptSync(password, salt, KEY_LEN);
if (hashBuffer.length !== test.length) return false;
return timingSafeEqual(hashBuffer, test);
}