const crypto = require('crypto');
// Function to hash a password with a salt
function hashPassword(password, salt) {
// Create hash object
const hash = crypto.createHash('sha256');
// Update with salt and password
hash.update(salt);
hash.update(password);
// Return digest
return hash.digest('hex');
}
// Generate a random salt
function generateSalt() {
return crypto.randomBytes(16).toString('hex');
}
// Example usage
const password = 'mySecurePassword123';
// For a new user, generate a salt and hash the password
const salt = generateSalt();
const hashedPassword = hashPassword(password, salt);
console.log('Password:', password);
console.log('Salt:', salt);
console.log('Hashed Password:', hashedPassword);
// To verify a password, hash it with the same salt and compare
function verifyPassword(password, salt, storedHash) {
const hash = hashPassword(password, salt);
return hash === storedHash;
}
// Check correct password
console.log('Verification with correct password:',
verifyPassword(password, salt, hashedPassword));
// Check incorrect password
console.log('Verification with incorrect password:',
verifyPassword('wrongPassword', salt, hashedPassword));
// Note: For production, use crypto.pbkdf2, bcrypt, scrypt, or Argon2 instead