23 lines
741 B
JavaScript
23 lines
741 B
JavaScript
import crypto from 'crypto';
|
|
/**
|
|
* Generate a cryptographically secure random string for authorization keys.
|
|
*/
|
|
export function generateSecureKey(length = 32) {
|
|
return crypto.randomBytes(length).toString('base64url');
|
|
}
|
|
/**
|
|
* Hash a plain text key with SHA-256 for secure database storage.
|
|
*/
|
|
export function hashKey(key) {
|
|
return crypto.createHash('sha256').update(key.trim()).digest('hex');
|
|
}
|
|
/**
|
|
* Constant-time hash verification to prevent timing attacks.
|
|
*/
|
|
export function verifyKeyHash(key, storedHash) {
|
|
const computedHash = hashKey(key);
|
|
if (computedHash.length !== storedHash.length)
|
|
return false;
|
|
return crypto.timingSafeEqual(Buffer.from(computedHash, 'hex'), Buffer.from(storedHash, 'hex'));
|
|
}
|