代码之家  ›  专栏  ›  技术社区  ›  Vish K

bcrypt始终返回false

  •  1
  • Vish K  · 技术社区  · 7 年前

    我正在尝试存储哈希密码并检查它是否有效。

    var bcrypt = require('bcrypt');
    let data = "";
    
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash("my password", salt, function(err, hash) {
            // Store hash in your password DB.
            console.log(hash);
            data = hash;
        });
    });
    
    bcrypt.compare("my password", data, function(err, res) {
        // res === true
        console.log(res)
    });
    

    返回值始终为false。?

    但如果我在genSalt函数中移动比较,它将返回true。

    谢谢

    1 回复  |  直到 7 年前
        1
  •  2
  •   coockoo    7 年前

    您正在节点中处理异步函数。js,所以这是预期的结果。为了更清楚地了解问题,请尝试 console.log 之前的数据 bcrypt.compare 。我可以肯定地说,它等于 ""

    然后尝试将比较函数移动到 .hash 回调函数

    var bcrypt = require('bcrypt');
    let data = "";
    
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash("my password", salt, function(err, hash) {
            // Store hash in your password DB.
            console.log(hash);
            data = hash;
            console.log(data); // Here data equals to your hash
            bcrypt.compare("my password", data, function(err, res) {
                // res === true
                console.log(res)
            });
        });
    });
    console.log('data') // Here data equals to initial value of ""
    

    您可以使用异步/等待函数使其看起来像同步代码,并消除回调。幸运的是 bcrypt 支持由使用的promise接口 async/await

    const salt = await bcrypt.genSalt(10);
    const hash = await bcrypt.hash("my password", salt);
    const result = await bcrypt.compare("my password", data);
    console.log(result);