Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jBCrypt for password hash comparison?

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?

like image 218
VNorman Avatar asked Mar 15 '12 14:03

VNorman


People also ask

Is bcrypt better than sha256?

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.

Does bcrypt generate same hash?

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.

Is bcrypt safe for passwords?

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.


1 Answers

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)

like image 196
Ren Avatar answered Oct 07 '22 15:10

Ren