2

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!

Tim__
  • 45
  • 1
  • 7

3 Answers3

2

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
Matt Goodrich
  • 4,875
  • 5
  • 25
  • 38
1

I have used crypto library for hashing and it works great. Here is my code snippet

var salt = crypto.randomBytes(128).toString('base64');
var iterations = 10;
var keylen = 20;
crypto.pbkdf2(args.password, salt, iterations, keylen, function(succes, bcryptedPassword) {
                    console.log(bcryptedPassword.toString());
                    //Do actions here

                });

Please check if it helps you or not

Seena V P
  • 934
  • 3
  • 9
  • 26
0

The following syntax is from the (abandoned?) bcrypt-nodejs module 1

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

You refer to the docs of the bcrypt module 2.

Make sure you're using the right module.

Fabian
  • 531
  • 4
  • 11