a66207ffa9
代码核销功能
21 lines
741 B
TypeScript
21 lines
741 B
TypeScript
import { randomBytes, scryptSync, timingSafeEqual } from 'crypto';
|
|
|
|
const SALT_LEN = 16;
|
|
const KEY_LEN = 64;
|
|
|
|
export function hashPassword(password: string): string {
|
|
const salt = randomBytes(SALT_LEN);
|
|
const hash = scryptSync(password, salt, KEY_LEN);
|
|
return `${salt.toString('hex')}:${hash.toString('hex')}`;
|
|
}
|
|
|
|
export function verifyPassword(password: string, stored: string): boolean {
|
|
const [saltHex, hashHex] = stored.split(':');
|
|
if (!saltHex || !hashHex) return false;
|
|
const salt = Buffer.from(saltHex, 'hex');
|
|
const expected = Buffer.from(hashHex, 'hex');
|
|
const actual = scryptSync(password, salt, expected.length);
|
|
if (actual.length !== expected.length) return false;
|
|
return timingSafeEqual(actual, expected);
|
|
}
|