JAVASCRIPT

Securely Hash Passwords Using Argon2 (Node.js)

Learn to securely hash user passwords with the Argon2 algorithm in Node.js, ensuring robust protection against brute-force attacks and Rainbow Tables.

const argon2 = require('argon2');

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

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

// Usage example
(async () => {
  const myPassword = 'mySecurePassword123!';
  const hashedPassword = await hashPassword(myPassword);

  if (hashedPassword) {
    const isCorrect = await verifyPassword(hashedPassword, myPassword);
    console.log('Verification Result (Correct):', isCorrect); // Should be true

    const isIncorrect = await verifyPassword(hashedPassword, 'wrongPassword');
    console.log('Verification Result (Incorrect):', isIncorrect); // Should be false
  }
})();
How it works: Storing passwords securely is paramount. This Node.js snippet demonstrates using `argon2`, a modern, highly secure hashing algorithm, to hash and verify user passwords. Argon2 is designed to resist brute-force and Rainbow Table attacks by being memory-hard and computationally intensive. The `argon2.hash` function generates a unique hash with automatically generated salts, and `argon2.verify` safely compares a plain password against a stored hash without exposing the original password.

Need help integrating this into your project?

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

Hire DigitalCodeLabs