[英]Bcrypt password compare with mysql and nodejs
我在編程方面不是很有經驗,我遇到了這個問題。
我正在嘗試創建一些安全性,當我在數據庫中創建用戶時,就會發生加密。 出於該項目的目的,我在數據庫中有一些普通密碼(未加密)和一些散列密碼(來自注冊的密碼)當我嘗試對用戶進行身份驗證時遇到了一個問題。 使用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!");
}
}
});
});
出於這個項目的目的,我在數據庫中有一些普通密碼(未加密)和一些散列密碼(來自注冊的密碼)
您可以在這里采取一些方法。
對密碼進行基本比較以及 hash 比較。
if (userPasw === password) {
req.session.loggedin = true;
// etc
} else {
// Your existing logic starting with bcrypt.compare(password, user) here
}
使用未散列的密碼遍歷數據庫中的任何行,並通過散列算法運行該密碼。 然后用結果更新數據庫。
要求使用未散列密碼的任何帳戶設置新密碼。
通常,您將通過正常的密碼重置流程來執行此操作(例如向用戶的 email 帳戶發送一次性令牌,他們可以使用該令牌訪問允許他們設置新密碼的頁面)。
要做好最后兩個選項中的任何一個,您需要知道哪些密碼被散列,哪些沒有。
如果您沒有該信息,那么您可以:
正如@Lelio Feieta 所說,最好對數據庫中的所有密碼進行加密,即使是為了安全也是如此。 這樣,當您已經在數據庫中擁有密碼時,它是可能的,它已經被加密,您可以更容易地比較它們,而不必將它們從一種格式傳遞到另一種格式。
我認為比較兩個密碼哈希的唯一方法是事先知道明文,然后應用算法。
例如:這就是密碼在數據庫中的存儲方式。
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.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.