我在编程方面不是很有经验,我遇到了这个问题。
我试图创建一些安全性,当我在数据库中创建一个用户时,加密就会发生。为了这个项目的目的,我在数据库中有一些普通密码(未加密)和一些哈希密码(注册时的密码),当我试图验证用户时,我遇到了一个问题。使用match = await bcrypt.compare(password,result[0].password)
,我只能比较散列密码来验证用户。但是对于没有散列的密码,不可能对它们进行比较。如何才能最好地解决这个问题?
loginRouter.post("/register", (req, res) => {
// register users with bcrypt password encryption
bcrypt.hash(req.body.password, saltRounds, (err, hashedPassword) => {
const { username, password } = req.body;
const sql = `INSERT INTO acc_users (username, password) VALUES ('${username}', '${hashedPassword}')`;
db.query(sql, (err, rows, fields) => {
if (!err) {
res.render("index");
} else {
console.log(err.message);
res.send(err);
}
});
});
});
loginRouter.post("/login", (req, res) => {
const user = req.body.username;
const password = req.body.password;
const sqlSearch = "SELECT * from acc_users WHERE username = ?";
const search_query = db.format(sqlSearch, [user]);
db.query(search_query, async (err, result) => {
if (err) throw err;
if (result.length == 0) {
} else {
//get the hashedPassword from result
const userPasw = result[0].password;
console.log(userPasw);
bcrypt.compare(password, user).then(function (result) {
// result == true
console.log(result);
});
match = await bcrypt.compare(password,userPasw)
// console.log(match)
// MATCH only works with hasshed passwords
// if (password === userPasw)
if (match) {
console.log(result);
console.log("---------> Login Successful");
console.log(password);
req.session.loggedin = true;
req.session.username = user;
res.send(`${user} is logged in!`);
} else {
console.log("---------> Password Incorrect");
res.send("Password incorrect!");
}
}
});
});
发布于 2022-08-01 13:03:33
正如@Lelio所说,最好将数据库中的所有密码都加密,即使是为了安全。这样,当您已经在数据库中拥有密码时,它已经被加密,并且您可以更容易地比较它们,而不必将它们从一种格式传递到另一种格式。
我认为比较两个密码散列的唯一方法是事先知道明文,然后应用该算法。
例:这就是如何将密码存储在数据库中。
const myPlaintextPassword = 'testpassword'.
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Here you store in the database
// Ex: hash = $2a$10$fKAyjaG0pCkisZfRpKsBxursD6QigXQpm1TaPBDZ4KhIZRguYPKHe
});
并进行比较
bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
// You compare with the user's password already stored in the database.
});
https://stackoverflow.com/questions/73193963
复制相似问题