提问人:Nicholas Oyagha 提问时间:11/17/2023 最后编辑:Nicholas Oyagha 更新时间:11/18/2023 访问量:35
(密码哈希)。我使用了 bcrypt 包。有没有其他方法可以实现这一目标?
( Passwords hash ). i used bcrypt package. is there another way to achieve this?
问:
将密码从纯文本转换为无法解密/解码的安全密码。我在这个例子中使用了(bcrypt 包)。我想知道是否有另一种方法可以使用不同的安全哈希算法 (SHA) 方法实现此目的?
const express = require("express");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const app = express();
const port = 3000;
// Middleware for parsing JSON requests
app.use(bodyParser.json());
// Sample user with a plain text password
const sampleUser = {
username: "exampleUser",
password: "userPassword123",
};
// Hash the password before storing it
bcrypt.hash(sampleUser.password, 10, (err, hash) => {
if (err) {
console.error("Error hashing password:", err);
} else {
sampleUser.hashedPassword = hash;
console.log("Hashed password:", hash);
}
});
// Route to authenticate a user
app.post("/login", (req, res) => {
const { username, password } = req.body;
// Assume sampleUser is retrieved from the database
if (username === sampleUser.username) {
bcrypt.compare(password, sampleUser.hashedPassword, (err, result) => {
if (err) {
console.error("Error comparing passwords:", err);
res.status(500).send("Internal Server Error");
} else if (result) {
res.status(200).send("Login successful!");
} else {
res.status(401).send("Authentication failed");
}
});
} else {
res.status(404).send("User not found");
}
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
答: 暂无答案
评论