gpt4 book ai didi

node.js - 比较两个密码哈希——nodejs

转载 作者:搜寻专家 更新时间:2023-10-31 22:40:46 26 4
gpt4 key购买 nike

我正在使用加密 https://nodejs.org/api/crypto.html用于密码加密和认证。我正在更改密码页面上工作,无法确定用户提供的密码是否与现有密码具有相同的哈希值。下面是我的代码。

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

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

最佳答案

我认为您的问题出在盐上。通常,您必须存储第一次用于散列的盐,并在第二次重复使用它。使用 salt 的原因是,如果某些黑客从受感染的系统(使用彩虹表攻击)中检索它,则确保哈希不会映射到原始通行证。参见 Why do we use the "salt" to secure our passwords?

如果你愿意尝试

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

关于node.js - 比较两个密码哈希——nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37278990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com