Inside a login Servlet, java, I hashed the password, entered as input by a user. Subsequently I have to compare the password entered as input and of which I obtained the hash, with the hash of the password stored on a MySql database.
Below, there is the Servlet code and the doPost method, within which I performed all the operations described above:
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// doGet (request, response);
LoginDao loginDao = new LoginDao ();
CheckPasswordDao checkPasswordDao = new CheckPasswordDao ();
String email = request.getParameter ("email");
byte [] password = request.getParameter ("password"). getBytes ();
try {
// generate the password hash
byte [] hashPassword = setHash (password);
if (checkPasswordDao.isHashValid (email, hashPassword)) {
response.sendRedirect ("welcome.jsp");
} else {
response.sendRedirect ("error.jsp");
}
} catch (Exception e) {
e.printStackTrace ();
}
}
The password hash saved on the database is of type BLOB. So I implemented password verification on a Dao class, as follows:
public class CheckPasswordDao
{
public boolean isHashValid (String email, byte [] hash_password) {
boolean status = false;
try {
Class.forName ("com.mysql.cj.jdbc.Driver");
String url = "jdbc: mysql: // localhost: 3306 /? User = root";
Connection connection = DriverManager.getConnection (url, "root", "mysqlRootPassword97!");
PreparedStatement ps = connection.prepareStatement(
"SELECT hash_password
FROM pwdb.passwords
WHERE email = ?;");
ps.setBytes (1, hash_password);
// always have to empty and clean the password
Arrays.fill (hash_password, (byte) 0);
ResultSet rs = ps.executeQuery ();
if (rs.next ()) {
System.out.println ("Password hash exists in DB.");
status = true;
} else {
System.out.println ("The password hash does NOT exist in the DB.");
}
connection.close ();
// REMEMBER: Implement the connection's close () method
} catch (SQLException e) {
e.printStackTrace ();
}
catch (Exception e1) {
System.out.println ("Error connecting DB." + E1.getMessage ());
}
return status;
}
}
With the query in the Dao class, I wonder if that specific hash password exists (generated in the Servlet class and then passed to the Dao), for the email entered by the user.
If I run the server, I get the error message, because it tells me that the password hash does not exist in the DB.
How can I compare the two passwords?
>Solution :
You’re doing:
"SELECT hash_password
FROM pwdb.passwords
WHERE email = ?;")
ps.setBytes (1, hash_password);
That doesn’t make sense, you’re looking for a record where the email equals your password?
This should probably be something like:
"SELECT 1
FROM pwdb.passwords
WHERE email = ? AND hash_password=?;")
ps.setString (1, email);
ps.setBytes (2, hash_password);