Use Nodejs's crypto module to add salt to your password hash

Source: Internet
Author: User


This article will explain to you how to useNode.jsthe Crypto module to add salt to your passwordhash. Here, we will not make a detailed comparison of the password storage methods that we do not understand. What we are going to do is to know theNode.jsmechanism of using salt in thehashpassword store. Rest assured, this is the best way to store passwords before other better methods appear.

What is this technology?


Adding salt is always the technique: the password entered by the user and a random string (the string is salt) are combined by a hash algorithm to generate a hash value and then store the result in the database.


Why do you want to add salt hash


Because the hash value of the same password is the same, it is easy to decipher the password by using the lookup tables and Rainbow tables (lookup Tables and Rainbow Talbes is a table in which some people pre-cracked some common passwords and then stored them for other people to use. If two or more users have the same password hash value , it will make it easier for the attacker to predict the password. Salt is added to allow the same hash value of the same password to be reduced. If your salt (random string) is long enough, then this chance will be almost zero.


to Practice

In practice you will do the following

Create and save a password
    1. Get user Password
    2. Generate a salt (random string)
    3. Combine salt and user passwords
    4. Hash encryption of a combined string using an encryption algorithm
    5. The result of the hash is stored as a password , along with the salt and password .
Verify user Password
    1. Verify the user name and obtain the hash password from the database for Salt
    2. Combine user-entered passwords with salt that the corresponding user has stored
    3. Using and creating users is the same hash encryption algorithm for hash encryption of associative strings
    4. Compare hash encrypted passwords to data-controlled stored passwords
Let's take a look at the actual code


The first step is to introducecryptothis module. You don't need to download it alone, because he's a built-in module for node. JS, just introduce it.


‘use strict‘var crypto = require(‘crypto‘)
Create a function to generate salt
/**
  *generate random string of characters i.e salt
  * @function
  * @param {number} length - Length of the random string.
  */
 
 
  Var genRandomString = function(length){
      Return crypto.randomBtytes(Math.ceil(length/2))
                 .toString(‘hex‘) /** converted to hex */
                 .slice(0,length);/**returns the specified length string*/
  }
Encrypt the password and salt with hash


Use a suitable cryptographic hash algorithm that you read in this article era, because with the development of computing power, cryptographic hashing technology will also develop. So if you're using a hash encryption algorithm, there's a big risk. Here we usesha512


/**
  * 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.createHamc(‘sha512‘, salt); /** uses the sha512 algorithm for hash*/
      Hash.update(password)
      Var value = hash.digest(‘hex‘)
      Return {
          Salt:salt,
          passwordHash:value
      }
   }


Below we will create a function that uses the function of the polygon to generate a hash value, stored as a user password in the database.


Function saltHashPassword(userpassword){
     Var salt = genRandowString(16) /**Generate a salt of length 16 characters*/
     Var passwordData = sha512(userpassword, salt);
     Console.log( console.log(‘UserPassword = ‘+userpassword);
     Console.log(‘Passwordhash = ‘+passwordData.passwordHash);
     Console.log(‘nSalt = ‘+passwordData.salt);)
}

saltHashPassword(‘MYPASSWORD‘);
saltHashPassword(‘MYPASSWORD‘);


Note that when wesaltHashPassworduse the same parameters two times, we just want to show that the results of two hash encryption using the same password are different.



Let's take a look at the full code show


‘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‘);


In running this code, you will get two different hash values (do not show here, interested can run their own look)


Conclusion


Whether you do any Web application that needs to store the user's password, it is very prone to problems, so here we strongly recommend that you use salt hash to process the user's password, which will effectively improve the security of password storage.



English original Address



Use Nodejs's crypto module to add salt to your password hash


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.