Skip to content

Instantly share code, notes, and snippets.

@theRemix
Last active February 16, 2020 21:02
Show Gist options
  • Save theRemix/257dfe4a07ad5434d41b9325c1314569 to your computer and use it in GitHub Desktop.
Save theRemix/257dfe4a07ad5434d41b9325c1314569 to your computer and use it in GitHub Desktop.
bcrypt example
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 'a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_';
console.log('password length', myPlaintextPassword.length)
// auto generate salt and hash
bcrypt.hash(myPlaintextPassword, saltRounds, (err, hash) => {
// Store hash in your password DB.
console.log('bcrypt salted hash:', hash)
});
// check password against hash stored in db
// pretend this is in db
const saltedHash = '$2b$10$qJ03iNNJ9E0TXGPc8tstjODGbcHiWiMB3jh4rQQcmwNRp3pKp.11G'
bcrypt.compare(myPlaintextPassword, saltedHash, (err, result) => {
console.log('correct password entered, checked against database, result:', result)
})
const incorrectPassword = 'incorrect passphrase'
bcrypt.compare(incorrectPassword, saltedHash, (err, result) => {
console.log('incorrect password entered, checked against database, result:', result)
})
const myTruncatedPlaintextPassword = 'a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_really_long_passphrase_a_';
console.log('truncated password length', myTruncatedPlaintextPassword.length)
bcrypt.compare(myTruncatedPlaintextPassword, saltedHash, (err, result) => {
console.log('correct truncated password entered, checked against database, result:', result)
console.log('bcrypt truncates passphrase to 72 before evaluating, this still passes even though the passphrase is not the full original passphrase')
})
// npm i -S bcrypt
// node bcrypt-example.js
password length 225
truncated password length 177
correct password entered, checked against database, result: true
bcrypt salted hash: $2b$10$nXz7zH8vE0GHlXxJNPFfUuA1lTnWhumYyyfw.MAz7pCDCmDQlSUi2
incorrect password entered, checked against database, result: false
correct truncated password entered, checked against database, result: true
bcrypt truncates passphrase to 72 before evaluating, this still passes even though the passphrase is not the full original passphrase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment