【问题标题】:How to return hashed password with bcrypt?如何使用 bcrypt 返回散列密码?
【发布时间】:2021-01-09 03:22:53
【问题描述】:

我正在使用 bcrypt,我正在尝试使用一个异步函数来散列密码并返回它,但由于它是异步的,除非我使用同步版本(即使它有效,我也不想要它)它返回 [object Promise]并且数据库将其保存为:{} 作为密码。是的,两个括号。我确实使用了await,但它不起作用,而且我对异步函数的理解很差。我在网上找不到任何答案,因为看起来我按照教程做得很好,但我显然不是。

代码如下所示:

function signup(){
     var pass = "example";
     pass = hashPassword(pass);
     
     console.log(pass); // prints [object Promise] - It's printed first.

     //write account with pass to database. Pass is saved as '{}'.
}

async function hashPassword(original_password){
     const hashedPass = await bcrypt.hash(original_password, 10);
     console.log(hashedPass) // prints the actual hashed pass - It's printed second

     return hashedPass; //returns [object Promise]
}

那么我怎样才能让它返回散列密码而不在异步中添加发送到数据库的代码?

【问题讨论】:

标签: node.js asynchronous bcrypt


【解决方案1】:

当您调用 async 函数时,它将返回 promise,请查看此 answer on SO

为了获得您的哈希数据,您可以使用.then 来解决您的承诺

hashPassword(pass).then(hash=>console.log(hash)).catch(err=>console.error(err))

或者你也可以使用async/await

async function signup() {
  try {
    var pass = "example";
    pass = await hashPassword(pass);
  } catch (err) {
    console.error(err);
  }
}

【讨论】:

  • 谢谢。我试过这样做var pass = data.pass.trim(); hashPass(pass).then((hash) => {pass = hash;}).catch(err=>console.error(err)); console.log("passtest:" + pass),它记录了 originalPass 而不是散列的。哈希函数是这样的:async function hashPass(originalPass){ const saltRounds = 10; const hashedPass = await bcrypt.hash(originalPass, saltRounds); return hashedPass; }
  • 这将返回 original password,因为 console.loghashPass 执行之前运行,因为您无法访问 then() 块之外的 async 变量
  • 哦,所以你是说我应该将密码发送到数据库,而我在 .then() 内??我只使用.then() 设置pass = hash 并稍后在.then() 之外使用新通行证
  • 您可以使用async/await 版本来满足您的需求,但如果您使用的是then(),则必须在.then() block 内进行操作
  • 好的,谢谢您的宝贵时间,这正是我所需要的。我接受了你的回答。
【解决方案2】:

bcrypt.hash 不返回承诺。

您可能需要将此函数调用包装到一个新的承诺中

const hashedPass = await new Promise((resolve, reject) => {
    bcrypt.hash(original_password, rounds, function(err, hash) {
      if (err) reject(err)
      resolve(hash)
    });

【讨论】:

  • 在这种情况下我不使用 return 吗?我之前尝试过包装它,因为我在网上看到了同样的建议,但我用的是return hash,而不是resolve(hash)
  • 如果我尝试你所做的,它会再次返回 [object Promise]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 2019-07-17
  • 1970-01-01
  • 2019-07-03
  • 2016-12-11
  • 2013-04-24
  • 1970-01-01
相关资源
最近更新 更多