JAVASCRIPT

Secure Password Hashing and Verification with Argon2 (Node.js)

Learn to securely hash and verify user passwords using the recommended Argon2 algorithm in Node.js, protecting against brute-force and rainbow table attacks.

const argon2 = require('argon2');

async function hashPassword(plainPassword) {
  try {
    return await argon2.hash(plainPassword);
  } catch (err) {
    console.error('Error hashing password:', err);
    throw new Error('Failed to hash password');
  }
}

async function verifyPassword(hashedPassword, plainPassword) {
  try {
    return await argon2.verify(hashedPassword, plainPassword);
  } catch (err) {
    console.error('Error verifying password:', err);
    return false; // Or throw error based on preference
  }
}

// Example Usage:
async function runExample() {
  const userPassword = 'mySecretPassword123!';
  const hashedPassword = await hashPassword(userPassword);
  console.log('Hashed Password:', hashedPassword);

  const isMatch = await verifyPassword(hashedPassword, userPassword);
  console.log('Password matches:', isMatch);

  const wrongMatch = await verifyPassword(hashedPassword, 'wrongPassword');
  console.log('Wrong password matches:', wrongMatch);
}

// runExample();
How it works: This snippet demonstrates how to use the 'argon2' library in Node.js for secure password hashing and verification. Argon2 is the recommended algorithm by the OWASP foundation due to its resistance against brute-force, rainbow table, and side-channel attacks. The 'hashPassword' function takes a plain password and returns a hashed version. The 'verifyPassword' function compares a plain password against a stored hash, returning true if they match and false otherwise, without revealing specific failure reasons. Always store only the hashed password, never the plain text.

Need help integrating this into your project?

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

Hire DigitalCodeLabs