Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
Created August 27, 2023 15:58
Show Gist options
  • Save dmorosinotto/00e179e7b73822cd6f847f24c0e566bd to your computer and use it in GitHub Desktop.
Save dmorosinotto/00e179e7b73822cd6f847f24c0e566bd to your computer and use it in GitHub Desktop.
Using BCrypt to hash password in Node.js
//READ MORE IN THIS ARTICLE https://morioh.com/a/782c0022755e/using-bcrypt-to-hash-passwords-in-nodejs EXPECIALLY PRE-REQUISITE
const bcrypt = require("bcrypt")
const saltRounds = 10
const password = "Admin@123"
//Password encryption + explicit Salt
bcrypt
.genSalt(saltRounds)
.then(salt => {
console.log('Salt: ', salt) // Salt: $2b$10$t7oxiwchWGHa/B9w0AzrYO
return bcrypt.hash(password, salt)
})
.then(hash => {
console.log('Hash: ', hash) // Hash: $2b$10$t7oxiwchWGHa/B9w0AzrYO2WH2rQbA86YSuQjSTmwIrpC/0ZXN7V2
})
.catch(err => console.error(err.message));
//Auto-generating a Salt and Hash
bcrypt
.hash(password, saltRounds)
.then(hash => {
console.log('Hash ', hash) // $2b$10$b63K/D03WFBktWy552L5XuibmiD5SxCrKg9kHCqOYaZwxRjIg14u2
//bcrypt hashing information $\[algorithm]$[cost]$[salt\][hash]
// - Algorithm: Will be "$2a$" or "$2b$" which means BCrypt
// - Cost: Represents the exponent used to determine how many iterations 2^n
// - Salt: (16-byte (128-bit)), base64 encoded to 22 characters
// - Hash: (24-byte (192-bit)), base64 encoded to 31 characters
validateUser(hash)
})
.catch(err => console.error(err.message))
//Using the bcrypt.compare function to verify Hash
function validateUser(hash) {
bcrypt
.compare(password, hash)
.then(res => {
console.log(res) // return true
})
.catch(err => console.error(err.message))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment