散列密码对我不起作用



我不知道为什么这个哈希密码代码不起作用。我确实安装了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 

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

要检查哈希值是否相等,需要用bcrypt.compare()测试,不能直接比较哈希值。有些库也称它为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);

相关内容

  • 没有找到相关文章

最新更新