Node.js Crypto Hash Password

Node.js Crypto Hash Password

  • 2016-08-27
  • 2428

This article will explain you to salt hash passwords using Node.js Crypto
Here we’ll not go into details comparing the pros and cons of different ways of storing passwords, rather we’ll see how we can implement salt hashing mechanism for storing passwords in NodeJS. Stay rest assured that this is one of the better ways if not the best way to store passwords.

What is this technique?

Salt hashing is a technique in which we take the user entered password and a random string of characters called as salt, hash the combined string with a sutaible hashing algorithm and store the result in the database.

Why Salt Hash?

Since hashes of the same password are the same, they are much easier to crack using lookup tables and rainbow tables, here someone pre-calculates the hashes of common passwords and stores them for others to use. Having same password hash for two or more users also makes it easier for the attacker to predict the password. So as a rule of thumb, no two users should have the same password hash. Adding salt to a password and then hashing the result reduces the possibility of having duplicate hashes and if your salt length is long enough, chances are minimal.

Practical Implementation

Well in practice you would do the following.

Creating and Storing password

  1. Take the user password
  2. Generate a salt(String of random characters)
  3. Combine the salt with the user entered password
  4. Hash the combined string with a suitable cryptographic algorithm.
  5. Store the result as the password and also store the salt along side.

Validating user password

  1. Validate the username and fetch the hashed result and salt from the database
  2. Combine the user entered password with the salt stored for that user.
  3. Hash the combined string with the same cryptographic algorithm used at the time of creating user.
  4. Compare the result with the stored hash.

In this article we won’t be building a complete end to end application, instead we will see the code to salt-hash passwords using Node.js Crypto

Lets See the code

First of all require the crypto module. You don’t need to install the module separately it is already available with Node.js, just require it.

index.js

'use strict';
var crypto = require('crypto');

Function to generate Salt

We will use crypto’s randomBytes function to generate a string of random character which will be used as salt.

index.js

/**
 * generates random string of characters i.e salt
 * @function
 * @param {number} length - Length of the random string.
 */
var genRandomString = function(length){
    return crypto.randomBytes(Math.ceil(length/2))
            .toString('hex') /** convert to hexadecimal format */
            .slice(0,length);   /** return required number of characters */
};

Hashing the password along with salt

Use a suitable hashing algorithm according to the time(year) you are reading this. With the surge in the computing power cryptographic hashing techniques are subject to compromise, so if you use an old hashing algorithm you might be running a security risk. Here we have used sha512.

index.js

/**
 * hash password with sha512.
 * @function
 * @param {string} password - List of required fields.
 * @param {string} salt - Data to be validated.
 */
var sha512 = function(password, salt){
    var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
    hash.update(password);
    var value = hash.digest('hex');
    return {
        salt:salt,
        passwordHash:value
    };
};

Now lets create a function that will use the above function to generate the hash that should be stored in the database as user’s password.

index.js

function saltHashPassword(userpassword) {
    var salt = genRandomString(16); /** Gives us salt of length 16 */
    var passwordData = sha512(userpassword, salt);
    console.log('UserPassword = '+userpassword);
    console.log('Passwordhash = '+passwordData.passwordHash);
    console.log('\nSalt = '+passwordData.salt);
}

saltHashPassword('MYPASSWORD');
saltHashPassword('MYPASSWORD');

Notice we are invoking the saltHashPassword twice with the same parameter value just to show you how the result of the hash would be different for the same user password.
Now lets have a look at the complete file all together.

index.js

'use strict';
var crypto = require('crypto');

/**
 * generates random string of characters i.e salt
 * @function
 * @param {number} length - Length of the random string.
 */
var genRandomString = function(length){
    return crypto.randomBytes(Math.ceil(length/2))
            .toString('hex') /** convert to hexadecimal format */
            .slice(0,length);   /** return required number of characters */
};

/**
 * hash password with sha512.
 * @function
 * @param {string} password - List of required fields.
 * @param {string} salt - Data to be validated.
 */
var sha512 = function(password, salt){
    var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
    hash.update(password);
    var value = hash.digest('hex');
    return {
        salt:salt,
        passwordHash:value
    };
};

function saltHashPassword(userpassword) {
    var salt = genRandomString(16); /** Gives us salt of length 16 */
    var passwordData = sha512(userpassword, salt);
    console.log('UserPassword = '+userpassword);
    console.log('Passwordhash = '+passwordData.passwordHash);
    console.log('\nSalt = '+passwordData.salt);
}

saltHashPassword('MYPASSWORD');
saltHashPassword('MYPASSWORD');

Run the code

To run the above code, navigate to the working directory and run the following command.
node index.js

You will get the similar output.

enter image description here

Note. The hash result should be stored into the database along with the salt used for the hash corresponding to each user, and the same technique should be applied while validating the user login.

Conclusion

If you are working on any web application that stores users password, it is very easy to get things wrong, here we saw how we can store passwords using salt-hash technique which is highly recommended, however it is a request to the readers to look up at recent techniques of storing passwords from the time you are reading this article.

Suggest

JavaScript with ReactJS and Nodejs

Node.js Tutorial with Visual Studio Code over 4 Hours

Node.js Tutorials: The Web Developer Bootcamp

Angular 2 and NodeJS - The Practical Guide to MEAN Stack 2.0

Complete Node JS Developer Course Building 5 Real World Apps