X

Node.js

Hashing Passwords with Bcrypt

July 22, 2021

/*

Using bcrypt.hash() to Hash Passwords


*/

Bcrypt is a package used to hash & compare string values. It's mostly used for passwords. It hashes & adds salt to your password making it harder to break. The hash is a scrambled representation of your password. The salt is a unique, random string of characters added to the beginning of the password, before it is hashed, known only to the key, which is the bcrypt package.

/*

Bcrypt.hash() parameters


*/

Bcrypt.hash() takes 3 parameters. The string that you want to hash. The number of rounds you want to run, known as saltRounds, the more rounds you do, the longer it takes the cpu to make the password, but it is also more difficult to break the password. Lastly, a callback function that takes an error object and the hash you created.

Code for bcrypt.hash()

/*

Using bcrypt.compare() to Compare Passwords


*/

We can compare the original password to the hashed password by using bcrypt.compare(). If the passwords match it will return a boolean value of true, if they don't it will return false.

/*

Bcrypt.compare() parameters


*/

The first parameter is the original password. The second parameter is the hashed password. The last is a callback function that takes an error object & the result of the match.

Code for bcrypt.compare() method

/*

Async, Await with Bcrypt


*/

I usually use bcrypt with express, whenever I need to compare the username & password of a user. You can use async, await with bcrypt.hash() & bcrypt.compare() to make it cleaner & nicer to look at it.

Code for async, await function using bcrypt.hash() & bcrypt.compare()

For more info on bcrypt, you can check out the docs here.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.