fork download
  1. const crypto = require('crypto');
  2.  
  3. // Function to generate a random salt of given length
  4. function generateSalt(length) {
  5. return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
  6. }
  7.  
  8. // Function to hash the password using SHA-256 and the provided salt
  9. function hash(password, salt) {
  10. const hash = crypto.createHmac('sha256', salt);
  11. hash.update(password);
  12. const hashedPassword = hash.digest('hex');
  13. return salt + hashedPassword; // Combining salt and hashed password
  14. }
  15.  
  16. // Function to compare the plain password with the hashed password
  17. function compare(password, hashed) {
  18. const salt = hashed.substr(0, 16); // Extracting the salt from the hashed password
  19. const hashedPassword = hash(password, salt); // Hashing the plain password with extracted salt
  20. return hashed === hashedPassword;
  21. }
  22.  
  23. // Example usage
  24. const plainPassword = 'mySecurePassword';
  25. const salt = generateSalt(16); // Generating a random salt
  26. const hashedPassword = hash(plainPassword, salt); // Hashing the password with the generated salt
  27.  
  28. console.log("Hashed Password:", hashedPassword);
  29.  
  30. // Bonus: Comparing the plain password with the hashed password
  31. const isMatch = compare(plainPassword, hashedPassword);
  32. console.log("Password Match:", isMatch);
  33.  
Success #stdin #stdout 0.1s 33416KB
stdin
Standard input is empty
stdout
Hashed Password: e244c1278e3651d772e4398424a322b3f4fbac45493c113d2d9af77fa6987eb0e9039bf42e3ee604
Password Match: true