Skip to content

Instantly share code, notes, and snippets.

@KenVega-Tekton
Created January 25, 2018 19:14
Show Gist options
  • Save KenVega-Tekton/9d7ef1ebd812b2e1afc2248358779ea3 to your computer and use it in GitHub Desktop.
Save KenVega-Tekton/9d7ef1ebd812b2e1afc2248358779ea3 to your computer and use it in GitHub Desktop.
Basic usage of bcrytpjs
const bcrypt = require("bcryptjs");
let password = "ThisRepresentsSomePassword123";
/*bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password, salt, (err, hash) => {
console.log(hash);
});
});*/
let hashedPassword =
"$2a$10$Fj6St8qtxek20BayFKYW1OR3kYN3WErSqp2yx74KjQtaNdgKpkUcq";
let hashedPassword2 =
"$2a$10$DafGKsNmwAnBv1Mm0/i86OP0fO2iE.r4exetr3lAw81/QXYjlAwM.";
bcrypt.compare(password, hashedPassword2, (err, result) => {
console.log(result);
});
@KenVega-Tekton
Copy link
Author

KenVega-Tekton commented Jan 25, 2018

Take a look at the following bcrypt hash I just created:

$2a$04$dph48qa9npG/d/k9HGNNPOWrcEPcV0bHyT5pmfHWiHQmi0YIlGiAO 

Let's break this up into it's proper parts:

$2a$04$  - This is specified that algorithm and the number of rounds to use. Not important for this conversation.
dph48qa9npG/d/k9HGNNPO  - This is the 22 character salt. It's stored right inline which means you don't need a separate database field to store the salt.
WrcEPcV0bHyT5pmfHWiHQmi0YIlGiAO  - This is the 31 character hash of the password (using the above salt).

Now that we know this, we can figure out what happens when someone tries to login to the application. We fetch the user by email and get the password field. The plain text password is then hashed with the 22 char salt. Bcrypt checks to see if that resulting hash is equal to the 31 character hash it has on file. If they're equal, the password was correct.

(this is a response from Andrew on the course Node.js)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment