// 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} 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} 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 })();