Utility Functions
Overview
The utils.js file provides utility functions for password hashing and verification, and for creating JSON Web Tokens (JWTs). These functions are essential for user authentication and security.
Dependencies
node:crypto: Provides cryptographic functionality, includingpbkdf2Syncfor key derivation,randomBytesfor generating random data, andtimingSafeEqualfor comparing buffers in a way that is safe from timing attacks.jsonwebtoken: A library for generating and verifying JSON Web Tokens.
Constants
iterations: The number of iterations to use for the PBKDF2 key derivation function. Set to100000.keylen: The length of the derived key in bytes. Set to64.digest: The hash function to use. Set tosha512.
hashPassword(password)
This asynchronous function takes a plain-text password and returns a hashed password string.
Functionality
- Generate Salt: It generates a 16-byte random salt and converts it to a hexadecimal string.
- Derive Key: It uses
pbkdf2Syncto derive a key from the password, salt, and other constants. - Format Hash: It returns a string containing the number of iterations, the salt, and the derived key, separated by colons.
Usage
import { hashPassword } from "./utils.js";
const password = "mysecretpassword";
const hashedPassword = await hashPassword(password);
// Store hashedPassword in the database
matchPassword(password, storedHash)
This asynchronous function compares a plain-text password with a stored hash to see if they match.
Functionality
- Parse Stored Hash: It splits the stored hash into its components: iterations, salt, and the stored derived key.
- Derive Key: It derives a key from the provided password and the extracted salt and iterations.
- Compare Keys: It uses
timingSafeEqualto compare the newly derived key with the stored derived key. This function is used to prevent timing attacks.
Usage
import { matchPassword } from "./utils.js";
const password = "mysecretpassword";
const storedHash = "100000:5f3...:a8b..."; // Retrieved from the database
const isMatch = await matchPassword(password, storedHash);
if (isMatch) {
// Passwords match
} else {
// Passwords do not match
}
mintJWT(user)
This function creates a JSON Web Token (JWT) for a given user.
Functionality
- Create Payload: It creates a payload containing the user's ID and role.
- Sign Token: It uses
jwt.sign()to create a JWT. The token is signed with a secret from theJWT_SECRETenvironment variable and has an expiration time defined by theEXPIRE_JWT_SECRETenvironment variable (defaulting to30d).
Usage
import { mintJWT } from "./utils.js";
const user = { _id: "12345", role: "admin" };
const token = mintJWT(user);
// Send the token to the client
Exports
hashPassword: The function for hashing passwords.matchPassword: The function for verifying passwords.mintJWT: The function for creating JWTs.