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

一世执手 提交于 2021-01-27 23:46:55

问题


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!


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/44797213/bcrypt-node-js-auto-gen-a-salt-and-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!