节点的 bcrypt Compare Returns False Though It's True

Node's bcrypt Compare Returns False Though It's True

这让我发疯。这是非常简单的代码:

user = new User(_.pick(userData, ['name', 'email', 'password']));
const salt = await bcrypt.genSalt(15);
user.password = await bcrypt.hash(user.password, salt);
const samePass = await bcrypt.compare(user.password, userData.password);

samePass 始终为假。我已经检查了示例请求密码和 https://bcrypt-generator.com 上的哈希值,它确实显示它们匹配。 bcrypt 总是返回 false。并且可以看到数据库没有任何关系

示例数据(我都使用 IDE 调试器在相同的 Pass 行设置断点):

user.password = b$nH2SGNZu9rdyz.V6qpT29eAhxKWfiOIr9ojOi96Ye2lQub.Pglof.
userData.password = oXmZ9pG5T4XtndH%#@A
user.password = await bcrypt.hash(user.password, salt); //This line is generating the password hash

比较时,您将第二个参数作为存储在数据库中的密码散列传递。但是,在您的代码中,您正在覆盖包含需要比较的实际密码的输入 user.password

const samePass = await bcrypt.compare(user.password, userData.password);

改为:

let passwordHash = await bcrypt.hash(user.password, salt);
const booleanResult = await bcrypt.compare(userData.password, passwordHash);

bcrypt.compare 接受两个参数:plaintextPasswordhashedPassword,顺序为

b$nH2SGNZu9rdyz.V6qpT29eAhxKWfiOIr9ojOi96Ye2lQub.Pglof.oXmZ9pG5T4XtndH%#@A 的散列版本,因此您可以这样做:

const password = 'oXmZ9pG5T4XtndH%#@A'
const preHashedPassword = 'b$nH2SGNZu9rdyz.V6qpT29eAhxKWfiOIr9ojOi96Ye2lQub.Pglof.'

await bcrypt.compare(password, preHashedPassword) // true

您也可以这样做:

const salt = await bcrypt.genSalt(15)
const newHashedPassword = await bcrypt.hash(password, salt)

await bcrypt.compare(password, newHashedPassword) // true

但您不能执行以下任何操作:

await bcrypt.compare(preHashedPassword, newHashedPassword) // false
await bcrypt.compare(newHashedPassword, preHashedPassword) // false
await bcrypt.compare(preHashedPassword, password) // false
await bcrypt.compare(newHashedPassword, password) // false

RunKit demo