如何比较bcrypt哈希密码

how to compare bcrypt hash password

我是 node js 的新手,我正在尝试验证一个加密的密码,我已经给出了以下我已经尝试过的代码。

async function passCheck(event) {
  // in event i am passing user entered password and email
  var EnteredPassword = bcrypt.hashSync(event.password, 10); //10 saltrounds

  var fromDB = await pool.query('SELECT password from User WHERE email  = ?', event.emailID);
  if (EnteredPassword == fromDB) {
    //Here i am comparing
    console.log('valid');
  } else {
    console.log('invalid');
  }
}

试试这个

  const auth = await bcrypt.compare(EnteredPassword , fromDB)
if(auth ){    
   console.log("valid");
}
else{
   console.log("invalid")

}

bcrypt 有一个用于比较哈希值的内置方法。

async function passCheck(event) {
  var fromDB = await pool.query('SELECT password from User WHERE email  = ? Limit 1', event.emailID);
  // --------------------------------------------------------------------------^
  // Added limit 1 to make sure the only one record will be returned.
  if (fromDB.length > 0 && await bcrypt.compare(event.password, fromDB[0].password)) {
    //Here i am comparing
    console.log('valid');
  } else {
    console.log('invalid');
  }
}

DB 结果集通常 returns 一个对象数组,因此,您应该检查是否有一些结果 (fromDB.length > 0),然后将散列字符串本身传递给比较方法。