比较两个密码哈希值 – nodejs

我正在使用encryptionhttps://nodejs.org/api/crypto.html进行密码encryption和身份validation。 我正在更改密码页面上工作,并且在确定用户提供的密码是否与现有密码具有相同的哈希值时遇到问题。 以下是我的代码。

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); 

我期待如果上面的控制台消息打印真正的现有用户密码匹配。 但是,这两个哈希似乎并不匹配。 请问我错过了什么? 如何做到这一点? 我想确保用户密码与他现有的密码相匹配,然后才能更换新密码。 任何帮助,将不胜感激。

我认为你的问题是在盐。 通常你必须储存你第一次使用的哈希值,并在第二次使用哈希值。 盐的原因是为了确保哈希不会映射到原来的通行证,如果一些黑客从受损系统(使用彩虹表攻击)检索它。 请参阅为什么我们使用“盐”来保护我们的密码?

如果你会尝试

 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的variables存储在为了响应http请求而调用的函数的范围之外),它就会工作。

更好的解决scheme(imo)是bcrypt正在做的事情。 在那里你为每个密码产生一个盐,但是为了validation密码是正确的,你使用比较,它使用存储在哈希中的salt。 通过这种方式,您可以对每个密码使用不同的盐,这意味着您不必担心盐会被泄漏。

 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和其他asynchronous变体。 另见: https : //www.npmjs.com/package/bcrypt-nodejs

  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 "); }