Compare two password hashes - nodejs

I use cryptography https://nodejs.org/api/crypto.html to encrypt and authenticate passwords. I am working on a page with a password for changes and I have a problem with determining whether the password provided by the user has the same hash as the existing password. Below is my code.

var createSalt = function createSalt() {
    return crypto.randomBytes(128).toString('base64');
};

var hashPwd = function hashPwd(salt, pwd) {
    var hmac = crypto.createHmac('sha256', salt);
    return hmac.update(pwd).digest('hex');
};

//use password , create salt, hash and compare with the existing
var salt = createSalt();
var passHash = hashPwd(salt,data.Password);
console.log('the password is', user.PassHash === passHash);

I expect the console message above to print true when the existing user password matches. However, the two hashes do not seem to match at all. Please, what am I missing? How to achieve this? I want the user password to match his existing password before he can change the new one. Any help would be greatly appreciated.

+4
2

, . , , . , , , - ( ). . "salt" ?

var salt = crypto.randomBytes(128).toString('base64');

var hashPwd = function hashPwd(salt, pwd) {
    var hmac = crypto.createHmac('sha256', salt);
    return hmac.update(pwd).digest('hex');
};

//use password , create salt, hash and compare with the existing
var passHash = hashPwd(salt,data.Password);
console.log('the password is', user.PassHash === passHash);

, ( salt var , http-).

(imo) - , bcrypt. , , , . , , , .

npm install bcrypt

...

var bcrypt = require('bcrypt');
var hash = bcrypt.hashSync("my password");

bcrypt.compareSync("my password", hash); // true
bcrypt.compareSync("not my password", hash); // false

compareAsync . . : https://www.npmjs.com/package/bcrypt-nodejs

+4
 UserSchema.pre('save', function (next) {
  if (this.password) {
    const salt = bcrypt.genSaltSync(10);//or your salt constant
    this.password = bcrypt.hashSync(this.password, salt);
  }
  next();
});

  const result = bcrypt.compareSync(req.body.password, your_hash_password);
      if (result){
        return res.json(message: "success");
      } else {
        return res.status(400).json("Bad request. Password don't match ");
      }
0

All Articles