【问题标题】:hashed password not works with me散列密码不适用于我
【发布时间】:2021-12-10 15:02:20
【问题描述】:

我不知道为什么这个哈希密码代码不起作用。 我确实安装了bcrypt,而且,如果密码相同,它应该转到(res.send("testing"))行,但无论如何在所有情况下密码都不匹配,即使它们相同。

这是我的代码:

const mysql = require('mysql');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = mysql.createConnection({
  host: process.env.DATABASE_host,
  user: process.env.DATABASE_user,
  password: process.env.DATABASE_password,
  database: process.env.DATABASE,
});

exports.form = (req, res) => {
  console.log(req.body);

  const { name, email, password, confirmPassword } = req.body;
  db.query(
    'SELECT email FROM users WHERE email=?',
    [email],
    async (error, results) => {
      if (error) {
        console.log(error);
      }

      if (results.length > 0) {
        return res.render('form', {
          message: 'that email is already in use',
        });
      } else if (password !== confirmPassword) {
        return res.render('form', {
          message: 'passwords not match',
        });
      }

      let hashedPassword = await bcrypt.hash('password', 8);
      console.log(hashedPassword);
      res.send('testing');
    }
  );
};
``

[enter image description here][1]


  [1]: https://i.stack.imgur.com/ToNvN.png

and always (passwords not match) comes even as u see in pic the passwords are same 

【问题讨论】:

  • 您只是说它不起作用,但究竟是什么错误以及您期望什么。详细询问。
  • 1-当我通过正确的相同密码登录时,我的控制台中应该会显示散列密码,但实际上即使密码相同,也会出现 else if (pass !== confirm pass) 条件,然后散列之后不工作 res.send 也不工作,我希望它现在清楚
  • 编辑后请查看帖子

标签: javascript node.js passwords


【解决方案1】:

每次调用bcrypt.hash() 都会得到不同的哈希字符串,即使密码相同,这是因为哈希是加盐的。

检查hash是否相等,需要用bcrypt.compare()进行测试,不能直接比较hash。一些图书馆也称它为bcrypt.verify()

编辑:假设您使用node.bcrypt.js 库:

const bcrypt = require('bcrypt');

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
let hashToStoreInDb = bcrypt.hashSync('mypassword', 10);

// Check if the entered login password matches the stored hash.
// The salt and the cost factor will be extracted from existingHashFromDb.
let existingHashFromDb = hashToStoreInDb;
const isPasswordCorrect = bcrypt.compareSync('mypassword', existingHashFromDb);

【讨论】:

  • const salt=await bcrypt.genSalt(2) const hashdPassword=await bcrypt.hash(password,salt);异步函数 compareIt(password){ const validPassword=await bcrypt.compare(password,hashdPassword); }
  • 我试试这个,但什么也没发生,如果你能告诉我或写在我的代码上
  • @HAJ - 添加了一个示例。为了简单起见,我使用了同步方法,当然你可以切换到异步方法。
猜你喜欢
  • 2012-06-12
  • 1970-01-01
  • 2018-12-10
  • 2018-05-16
  • 1970-01-01
  • 2014-11-25
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多