I am having trouble getting a plaintext password and a previous hash to match using BCrypt's checkpw(plaintextpw, previoushash) method.
In a register servlet I take the entered password, hash it using BCrypt's hashpw(password, genSalt) method and store it in a db.
In the login servlet I take that hash from the db, and use BCrypt's checkpw to see if it matches the entered password.
It never matches. This works fine in my regular java app, just not in the webapp. No one else is having this problem so I figure I must be doing it wrong:
//RegisterServlet
String pw_hash = BCrypt.hashpw(request.getParameter("password"), BCrypt.gensalt());
String loginInsertString = "insert into login (loname,lopassword,locustomerid)" +
" VALUES ('" + username + "','" + pw_hash + "','" + loginInsert + "');";
//LoginServlet
ResultSet rs = stmt.executeQuery("select lopassword from login where loname = '" +
loginName + "';");
while( rs.next()){
dbhash = rs.getString(1);
}
out.println(dbhash+"<br>");
if (BCrypt.checkpw(request.getParameter("password"), dbhash)) {
out.println("It matches");
}else{
out.println("It does not match");
}
The BCrypt API is very simple - here
I'm not storing the salt because with BCrypt you supposedly don't have to - so what am I doing wrong?
Bcrypt was not designed for encrypting large amounts of data. It is best implemented for passwords, however SHA-256 is better for large amounts of data because it is less costly and faster.
Bcrypt uses adaptive hash algorithm to store password which is a one-way hash of the password. BCrypt internally generates a random salt while encoding passwords and store that salt along with the encrypted password. Hence it is obvious to get different encoded results for the same string.
The takeaway is this: bcrypt is a secure algorithm but remember that it caps passwords at 72 bytes. You can either check if the passwords are the proper size, or opt to switch to argon2, where you'll have to set a password size limit.
The database field the pw_hash was stored in was 80 characters. This was 20 characters more than a BCrypt hash. Trimming the hash or resetting the database field to 60 characters worked.
(Posting the given answer [see comments on question] to remove the question from the unanswered queue. User was asked nearly a year ago to do this but has not done so yet. Credit for this answer is theirs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With