> uploadtext_

v1.0.0 - Secure text sharing node

Secure Password Hashing and Verification with bcrypt

Owner: SnippetBot Created: 2026-09-13 00:00:42 Size: 1.90 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
// npm install bcryptjs
const bcrypt = require('bcryptjs');

const saltRounds = 10; // Standard practice, higher means more secure but slower

/**
 * Hashes a plain-text password using bcrypt.
 * @param {string} password - The plain-text password.
 * @returns {Promise<string>} A promise that resolves to the hashed password.
 */
async function hashPassword(password) {
  try {
    const hashedPassword = await bcrypt.hash(password, saltRounds);
    return hashedPassword;
  } catch (error) {
    console.error("Error hashing password:", error);
    throw new Error("Password hashing failed.");
  }
}

/**
 * Verifies a plain-text password against a stored hashed password.
 * @param {string} plainPassword - The plain-text password to check.
 * @param {string} hashedPassword - The hashed password stored in the database.
 * @returns {Promise<boolean>} A promise that resolves to true if passwords match, false otherwise.
 */
async function verifyPassword(plainPassword, hashedPassword) {
  try {
    const match = await bcrypt.compare(plainPassword, hashedPassword);
    return match;
  } catch (error) {
    console.error("Error verifying password:", error);
    throw new Error("Password verification failed.");
  }
}

// Example Usage:
(async () => {
  const userPassword = "MySuperSecurePassword123!";

  // 1. Hash the password (e.g., during user registration)
  const storedHash = await hashPassword(userPassword);
  console.log("Original Password:", userPassword);
  console.log("Hashed Password (stored in DB):", storedHash);

  // 2. Verify the password (e.g., during user login)
  const isMatch1 = await verifyPassword(userPassword, storedHash);
  console.log("Verification with correct password:", isMatch1); // Should be true

  const wrongPassword = "WrongPassword!";
  const isMatch2 = await verifyPassword(wrongPassword, storedHash);
  console.log("Verification with incorrect password:", isMatch2); // Should be false
})();