You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中使用Argon2验证密码始终返回True的问题排查

Argon2 verify() always returns true no matter what I compare in Node.js

Problem Description

我在Node.js中使用Argon2库做密码验证,但遇到了一个奇怪的问题——不管我把哈希值和什么内容对比,argon2.verify()看起来始终返回true。以下是我的相关代码:

global.user = [{username:"u1", password:"hidden"}]; 
// run the password in the argon2 hashing alg 
const signup = async function(password) { 
 // hash password using argon2i (mainly for passwords) 
 var key = await argon2.hash(password, { 
 type: argon2.argon2i, 
 timeCost: 200, 
 hashLength: 128, 
 }); 
 return key; 
} 
var k = signup(req.body.password); 
k.then(function(result) { 
 console.log(result); 
 global.user.push({username:req.body.username, password:result}) 
 res.json(global.user); 
}) 
var success = false; 
if(argon2.verify(item.password, "meow")) { 
 console.log(req.body.password); 
 console.log(item.password); 
 success = true; 
}

我搞不清楚哪里出问题了,希望有人能帮我排查一下。


Solution

你遇到的问题核心在于错误地把异步的argon2.verify()当成同步函数来使用,这是Node.js异步编程里很容易犯的错误。

问题根源

  • argon2.verify()是异步方法,它返回的不是直接的布尔值,而是一个Promise对象。
  • 在JavaScript的条件判断中,任何非空对象(包括Promise)都会被视为truthy(真值),所以不管验证逻辑是否正确,if(argon2.verify(...))这个条件永远都会成立,看起来就像verify总是返回true。

正确实现方式

你需要用async/await或者.then()的方式来处理verify的异步结果:

方式1:使用async/await(更易读)

// 把验证逻辑包裹在异步函数中
async function checkPassword(item) {
  let success = false;
  try {
    // 注意参数顺序:第一个是哈希值,第二个是要验证的明文密码
    success = await argon2.verify(item.password, "meow");
    if (success) {
      console.log(req.body.password);
      console.log(item.password);
      console.log("密码验证成功!");
    } else {
      console.log("密码验证失败!");
    }
  } catch (err) {
    // 处理哈希格式无效等验证错误
    console.error("验证出错:", err);
  }
  return success;
}

// 调用异步函数
checkPassword(item);

方式2:使用.then()链式调用

let success = false;
argon2.verify(item.password, "meow")
  .then(isValid => {
    success = isValid;
    if (success) {
      console.log(req.body.password);
      console.log(item.password);
      console.log("密码验证成功!");
    } else {
      console.log("密码验证失败!");
    }
  })
  .catch(err => {
    console.error("验证出错:", err);
  });

额外注意事项

  • Argon2类型推荐:虽然你目前使用的是argon2i,但argon2id现在是更优选择——它兼顾了抗侧信道攻击和抗暴力破解的能力。你可以把哈希配置改成type: argon2.argon2id。
  • 全局变量风险:用global.user存储用户数据在生产环境中非常不安全——服务重启或多进程部署时数据会丢失,建议改用数据库来持久化存储用户信息。

内容的提问来源于stack exchange,提问作者Justin Case

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:25:54