简体   繁体   中英

Bcrypt password compare with mysql and nodejs

I am not very experienced in programming and I came into this problem.

I am trying to create some security and when I create a user inside the database the encryption takes place. For the purpose of this project I have some normal passwords inside the database ( not encrypted ) and some hashed password ( the one from registration ) When I try to authenticate the user I came across an issue. With match = await bcrypt.compare(password,result[0].password) I am only able to compare the hashed password to authenticate the user. But for the password that are not hashed is not possible to compare them. How is the best aproach to solve this issue?

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!");
      }
    }
  });
});

For the purpose of this project I have some normal passwords inside the database ( not encrypted ) and some hashed password ( the one from registration )

There are a few approaches you can take here.

The insecure approach

Do a basic comparison of the password as well as a hash comparison.

if (userPasw === password) {
    req.session.loggedin = true;
    // etc
} else {
    // Your existing logic starting with bcrypt.compare(password, user) here
}

The middleground

Loop through any row in the database with an unhashed password and run that passwork through your hashing algorithm. Then update the database with the result.

The secure approach

Require any account using an unhashed password to set a new password.

Typically you'll do this through a normal password reset flow (such as sending a one time token to the user's email account that they can use to access a page that allows them to set a new password).


To do either of the last two options well you'll need to know which passwords were hashed and which were not.

If you don't have that information, then you can:

  • Tell people who have failed login attempts that you have upgraded your password security and, as a consequence, accounts with passwords set before you did that need to reset them.
  • Force everybody to reset their passwords

As @Lelio Feieta says, it is best to have all passwords in the database encrypted, even for security. That way, it is possible when you already have the password in the database, it is already encrypted and you can compare them easier, without having to pass them from one format to another.

The only way I think to compare two password hashes is to know the plaintext beforehand and then apply the algorithm.

Ex: This is how the password would be stored in the database.

const myPlaintextPassword = 'testpassword'.
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
  // Here you store in the database
  // Ex: hash = $2a$10$fKAyjaG0pCkisZfRpKsBxursD6QigXQpm1TaPBDZ4KhIZRguYPKHe
});

And to compare

bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
  // You compare with the user's password already stored in the database.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM