I am currently using the following for hashing passwords:

var pass_shasum = crypto.createHash('sha256').update(req.body.password).digest('hex');

Could you please suggest improvements to make the project safer?


I use the follwing code to salt and hash passwords.

var bcrypt = require('bcrypt');

exports.cryptPassword = function(password, callback) {
   bcrypt.genSalt(10, function(err, salt) {
    if (err) 
      return callback(err);

    bcrypt.hash(password, salt, function(err, hash) {
      return callback(err, hash);
    });
  });
};

exports.comparePassword = function(plainPass, hashword, callback) {
   bcrypt.compare(plainPass, hashword, function(err, isPasswordMatch) {   
       return err == null ?
           callback(null, isPasswordMatch) :
           callback(err);
   });
};

bcrypt also can be called synchronously. Sample Coffeescript:

bcrypt = require('bcrypt')

encryptionUtil = 
    encryptPassword: (password, salt) ->
        salt ?= bcrypt.genSaltSync()
        encryptedPassword = bcrypt.hashSync(password, salt)
        {salt, encryptedPassword}

    comparePassword: (password, salt, encryptedPasswordToCompareTo) ->
        {encryptedPassword} = @encryptPassword(password, salt)
        encryptedPassword == encryptedPasswordToCompareTo

module.exports = encryptionUtil

Also there is bcrypt-nodejs module for node. https://github.com/shaneGirish/bcrypt-nodejs.

Previously I used already mentioned here bcrypt module, but fall into problems on win7 x64. On the other hand bcrypt-nodejs is pure JS implementation of bcrypt and does not have any dependencies at all.


bcrypt with typescript

npm i bcrypt
npm i -D @types/bcrypt
 import * as bcrypt from 'bcrypt';

export const Encrypt = {

    cryptPassword: (password: string) =>
        bcrypt.genSalt(10)
        .then((salt => bcrypt.hash(password, salt)))
        .then(hash => hash),
    
        comparePassword: (password: string, hashPassword: string) =>
            bcrypt.compare(password, hashPassword)
            .then(resp => resp)
    
    }

Exemple: Encrypt

const myEncryptPassword = await Encrypt.cryptPassword(password);

Exemple: Compare

const myBoolean = await Encrypt.comparePassword(password, passwordHash);