简体   繁体   中英

NodeJs - callback is not defined - How do I use async for password hashing?

I'm fairly new to nodeJS, and I've been tasked with creating a sample registration page, and with it, my attempts at encrypting the user's password.

Here's what I came up with, used by simply passing the user's password:

function hashPassword(password) {
  var salt = crypto.randomBytes(128).toString('base64')
  var iterations = 1000;
  var hash = crypto.pbkdf2Sync(password, salt, iterations, 512, 'sha512');
  return {
    salt: salt,
    hash: hash.toString('base64'),
    iterations: iterations
  };
}

Now, I heard that it's best practice to use async on functions that may take awhile, but unfortunately I'm rather new to async on JS.

Here's what I came up with through google searches ( specifically, here ), but I neither understand it completely nor could I get it to work. Keeps saying ReferenceError: callback is not defined :

function hashPassword(password, callback) {
  var saltBytes = 128;
  var iterations = 1000;
  var hashBytes = 512
  crypto.randomBytes(saltBytes, (err, salt) => {
    if (err) {
      return callback(err);
    }

    crypto.pbkdf2(password, salt, iterations, hashBytes, 'sha512', (err, hash) => {
      if (err) {
        return callback(err);
      }

      var combined = new Buffer(hash.length + salt.length + 8);
      combined.writeUInt32BE(salt.length, 0, true);
      combined.writeUInt32BE(iterations, 4, true);

      salt.copy(combined, 8);
      hash.copy(combined, salt.length + 8);
      callback(null, combined);
    });
  });
}

As far as my limited knowledge of async goes, it's in the callback function I'm supposed to do whatever else is required (in my case, save to DB).

What did I do wrong, or what am I not getting?

Are you calling your function like this ?

hashPassword('password here', function (error, combined) {
  if(error) {
    // handle error
  } else {
    // do something with combined
  }
});

I think the error is because you are not sending the callback function as second parameter when you call hashPassword function

Check this gist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM