javascript - 散列密码不适用于我
问题描述
我不知道为什么这个哈希密码代码不起作用。我确实安装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);
推荐阅读
- ios - 错误域=AVFoundationErrorDomain 代码=-11800
- java - 如何修复 java.lang.AbstractMethodError: org.apache.xerces.dom.DeferredElementNSImpl.getTextContent()Ljava/lang/String;
- javascript - JavaScript。从多维数组推送和读取
- php - 如何在 shell 中跟踪浏览器触发的 PHP 脚本?
- jquery - wc_get_product(Product_id) 在 ajax 调用的文件中不起作用?
- ios - 将 Square UIImage 转换为圆形 UIIMage 以与 CAEmitterCell.contents 一起使用
- swift - 无法将“日期”类型的值转换为预期的参数类型“日期”
- c# - 在 WPF 中设置 DynamicResouce 图标的颜色
- java - Gradle 构建:Java - 编译器错误
- java - java.lang.ClassNotFoundException 未指定缺少的类