diff --git a/backend/src/lib/password.ts b/backend/src/lib/password.ts new file mode 100644 index 0000000..ded9a17 --- /dev/null +++ b/backend/src/lib/password.ts @@ -0,0 +1,18 @@ +import { randomBytes, scryptSync, timingSafeEqual } from "crypto"; + +const keyLength = 64; + +export function hashPassword(password: string) { + const salt = randomBytes(24).toString("hex"); + const hash = scryptSync(password, salt, keyLength).toString("hex"); + return `scrypt$${salt}$${hash}`; +} + +export function verifyPassword(password: string, storedHash: string | null | undefined) { + if (!storedHash) return false; + const [algorithm, salt, hash] = storedHash.split("$"); + if (algorithm !== "scrypt" || !salt || !hash) return false; + const expected = Buffer.from(hash, "hex"); + const actual = scryptSync(password, salt, expected.length); + return expected.length === actual.length && timingSafeEqual(expected, actual); +}