JAVASCRIPT

Securely Hash Passwords with Argon2 in Node.js

Learn to securely hash user passwords using the Argon2 algorithm with Node.js `argon2` library, preventing common brute-force and rainbow table attacks.

const argon2 = require('argon2');

async function hashPassword(password) {
  try {
    const hash = await argon2.hash(password, {
      type: argon2.argon2id, // Recommended type
      memoryCost: 2 ** 16,  // 64MB
      timeCost: 4,         // iterations
      parallelism: 1       // threads
    });
    console.log('Hashed Password:', hash);
    return hash;
  } catch (err) {
    console.error('Error hashing password:', err);
    throw err;
  }
}

async function verifyPassword(hash, password) {
  try {
    const match = await argon2.verify(hash, password);
    console.log('Password Match:', match);
    return match;
  } catch (err) {
    console.error('Error verifying password:', err);
    throw err;
  }
}

// Example Usage:
(async () => {
  const userPassword = 'mySecretPassword123!';
  const hashedPassword = await hashPassword(userPassword);
  
  if (hashedPassword) {
    // Later, when a user tries to log in:
    const isCorrect = await verifyPassword(hashedPassword, userPassword);
    console.log('Login attempt with correct password:', isCorrect);
    
    const isIncorrect = await verifyPassword(hashedPassword, 'wrongPassword');
    console.log('Login attempt with incorrect password:', isIncorrect);
  }
})();
How it works: This Node.js snippet demonstrates secure password hashing and verification using the `argon2` library, which implements the Argon2 algorithm, an award-winning standard for password hashing. The `hashPassword` function takes a plain-text password and uses `argon2id` (a hybrid version suitable for both side-channel attack resistance and GPU cracking resistance) along with configurable memory cost, time cost, and parallelism to generate a strong, salted hash. The `verifyPassword` function then safely compares a provided plain-text password against a stored hash without revealing the original password, safeguarding against rainbow table attacks and making brute-force attacks computationally intensive.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs