Getting started with Node.js and bcrypt

November 24, 2015

Stock encryption image

For those of you looking for a safe way to store user passwords in your Node.js application, look no further!

Introducing bcrypt.

This Node package uses the UNIX bcrypt library first invented in 1999. It allows you to hash and encrypt sensitive data like user passwords before storing them in your database.

Let’s check out an example!

First you’ll want to install bcrypt and save it to your current project

npm install bcrypt --save

Then, inside your node app, create a salt and use the hashSync method to turn a plain text password into an encrypted hash.

// Your node app

// Require the bcrypt package
var bcrypt = require('bcrypt');

// Create a password salt
var salt = bcrypt.genSaltSync(10);

// Salt and hash password
var passwordToSave = bcrypt.hashSync(passwordFromUser, salt)

Last, whenever you need to pull a password out of your database and check it against one the user entered ( like when they are trying to log back in! ) just do something like this:

// Grab user from your database - this example uses MysQL
connection.query("SELECT * FROM users WHERE username = ?",
    [usernameEnteredByUser],
    function(err, rows) {
        if (err) {
            return done(err);
        }

        if (bcrypt.hashSync(passwordEnteredByUser, salt) === rows[0].password) {
          // Yay, it worked!
        }
});

This should provide you an easy solution for storing and retrieving passwords in a way that is safe. Even if your databases are compromised, any attackers would only get access to the salted and hashed passwords.