Using Bcrypt to Hash Passwords
password hashes
instead of actual passwords when storing our User’s access credentials in our databases incase of hackers trying to inject SQL queries.What is Cryptography?
Cryptography
: Way to use algorithms and secret keys to keep information secure.
Encryption
.Adversaries
: Third-parties attempting to steal user identities.What is encryption?
How does encryption work?
symmetric
and asymmetric
.Symmetric
Asymmetric
Public Key
: Shared with anyone wanting to encrypt a message for the recipient.Private Key
: Used to decrypt the message.When is it appropriate to use encryption?
What is hashing?
Hashing
: The process of converting a message of any length into a short fixed-length string.
salting
can be used to deal with different users using the same password.
When is it appropriate to use hashing?
Password Digest
: Common term to refer to a hashed password.Using Bcrypt to hash user passwords
bcryptjs
npm install bcryptjs
const bcrypt = require('bcryptjs');
Await your hash method to generate a hashed value.
Hash method takes in the user password, and # of rounds for salt.
Log in a user by comparing password and hash value.
Misc. Notes on Bcrypt
Example of a full async implementation:
const bcrypt = require("bcryptjs");
async function getHash(password, saltRounds) {
const hash = await bcrypt.hash(password, saltRounds);
console.log(hash);
return hash;
}
async function isPassword(password, hash) {
const isPassword = await bcrypt.compare(password, hash);
console.log(isPassword);
return isPassword;
}
(async () => {
const hashedPassword = await getHash("P@ssw0rd", 10);
const passwordIsMatch = await isPassword("P@ssw0rd", hashedPassword);
})();
const saltRounds = 10;
const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync("B4c0//", salt);
bcrypt.compareSync("B4c0//", hash); // true
bcrypt.compareSync("not_bacon", hash); // false