Search code examples
node.jshashbcryptsalt-cryptography

bcrypt node.js (auto-gen a salt and hash)


I am using the following code to hash (and hopefully salt) user passwords before I store them in my DB.

// hash the password before the user is saved
ConsultantSchema.pre('save', function(next) {
  var user = this;

  // hash the password only if the password has been changed or user is new
  if (!user.isModified('password')) return next();

  // generate the hash
  bcrypt.hash(user.password, null, null, function(err, hash) {

    if (err) {
      logger.error("bcrypt.hash "+err);
      return next(err);
    } 

    // change the password to the hashed version
    user.password = hash;
    next();
  });
});

What I am confused about, is the part

bcrypt.hash(user.password, null, null, function(err, hash) {

I got this code from a tutorial and I have seen it quite often searching for an answer. Based on the documentation (https://www.npmjs.com/package/bcrypt) for bcrypt I would have expected the following code

const saltrounds = 10;
bcrypt.hash(user.password, saltRounds, function(err, hash) {

To be working but this breaks my program without an error.

My questions are: Why are there two "null" arguments? What are they for? Is the hash salted based on the code with the two nulls?

Thank you in advance for you help!


Solution

  • There is a difference between bcrypt and bcrypt-nodejs. The following code is from their docs at npmjs.com.

    bcrypt hashing

    bcrypt.hash(myPlaintextPassword, salt, function(err, hash)
    

    or

    bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash)
    

    bcrypt-nodejs hashing

    bcrypt.hash(myPlaintextPassword, null, null, function(err, hash)
    

    Explanation

    You are looking at the docs for bcrypt, not bcrypt-nodejs. If you are using node.js, you'll most likely want to use bcrypt-nodejs. I have multiple projects utilizing its features. The two null fields are for the salt and progress:

    • salt - [REQUIRED] - the salt to be used to hash the password.
    • progress - a callback to be called during the hash calculation to signify progress