JAVASCRIPT
Securely Hashing Passwords with Argon2 in Node.js
Learn how to securely hash and verify user passwords using the Argon2 algorithm in Node.js, a modern and recommended approach for credential storage.
const argon2 = require('argon2');
// Function to hash a password
async function hashPassword(password) {
try {
const hash = await argon2.hash(password, {
type: argon2.Argon2id, // Recommended type for general use
memoryCost: 2 ** 16, // 65536 KB
timeCost: 2, // Iterations
parallelism: 1 // Number of threads
});
return hash;
} catch (err) {
console.error('Error hashing password:', err);
throw new Error('Failed to hash password.');
}
}
// Function to verify a password against a hash
async function verifyPassword(hash, password) {
try {
if (await argon2.verify(hash, password)) {
return true; // Password matches
} else {
return false; // Password does not match
}
} catch (err) {
console.error('Error verifying password:', err);
throw new Error('Failed to verify password.');
}
}
// Example Usage:
async function main() {
const userPassword = 'mySecurePassword123!';
// 1. Hash the password
console.log('Hashing password...');
const hashedPassword = await hashPassword(userPassword);
console.log('Hashed Password:', hashedPassword);
// 2. Verify the password
console.log('
Verifying correct password...');
const isMatch = await verifyPassword(hashedPassword, userPassword);
console.log('Password matches:', isMatch);
console.log('
Verifying incorrect password...');
const isMismatch = await verifyPassword(hashedPassword, 'wrongPassword');
console.log('Password matches:', isMismatch);
}
main();
How it works: Storing passwords directly in a database is highly insecure. Instead, they should always be hashed. This snippet demonstrates how to securely hash and verify passwords using Argon2, a modern, robust, and industry-recommended password hashing function, in Node.js. It uses the `argon2` library, configured with reasonable parameters for `memoryCost`, `timeCost`, and `parallelism` to make brute-force attacks computationally expensive, significantly enhancing the security of user credentials.