const crypto = require('crypto');
// Secure password hashing with PBKDF2
function hashPasswordSecure(password, salt, iterations = 100000) {
return new Promise((resolve, reject) => {
crypto.pbkdf2(
password,
salt,
iterations,
64, // Key length in bytes
'sha512', // Hash function
(err, derivedKey) => {
if (err) reject(err);
resolve(derivedKey.toString('hex'));
}
);
});
}
// Generate a random salt
function generateSalt() {
return crypto.randomBytes(16).toString('hex');
}
// Example usage
async function example() {
try {
const password = 'mySecurePassword123';
// For a new user, generate a salt and hash the password
const salt = generateSalt();
const iterations = 100000; // Higher is more secure but slower
console.log('Password:', password);
console.log('Salt:', salt);
console.log('Iterations:', iterations);
const hashedPassword = await hashPasswordSecure(password, salt, iterations);
console.log('Hashed Password:', hashedPassword);
// To verify a password
const verifyCorrect = await hashPasswordSecure(password, salt, iterations) === hashedPassword;
console.log('Verification with correct password:', verifyCorrect);
const verifyWrong = await hashPasswordSecure('wrongPassword', salt, iterations) === hashedPassword;
console.log('Verification with incorrect password:', verifyWrong);
} catch (error) {
console.error('Error:', error.message);
}
}
// Run the example
example();