Node.js hashing of passwords

alditis picture alditis · Dec 24, 2012 · Viewed 58.5k times · Source

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?

Answer

balazs picture balazs · Dec 24, 2012

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