Skip to content

Commit

Permalink
feat: Text hashing utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisGV04 committed Mar 6, 2024
1 parent 8d183ac commit e7d761a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './errors';
export * from './locales';
export * from './plugins';
export * from './utils';
33 changes: 33 additions & 0 deletions src/utils/hash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';

const scryptAsync = promisify(scrypt);

/**
* Function to hash any plain string
* @param text Plain string to convert into a hash
* @returns Hashed version of the string
*/
export async function hashText(text: string) {
const salt = randomBytes(10).toString('hex');
const buf = (await scryptAsync(text, salt, 64)) as Buffer;

return `${buf.toString('hex')}.${salt}`;
}

/**
* Function to check if a plain string is equal to a hashed string
* @param storedHash The hashed version of a string
* @param supplied Plain string to compare against the hash
* @returns Whether or not both strings match
*/
export async function compareHash(storedHash: string, supplied: string) {
const [hashedText, salt] = storedHash.split('.');
if (!hashedText || !salt) return false;

const buf = (await scryptAsync(supplied, salt, 64)) as Buffer;
const keyBuffer = Buffer.from(hashedText, 'hex');
const match = timingSafeEqual(buf, keyBuffer);

return match;
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './hash';

0 comments on commit e7d761a

Please sign in to comment.