How to use jBCrypt for password hash comparison?

VNorman picture VNorman · Mar 15, 2012 · Viewed 9.6k times · Source

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?

Answer

Ren picture Ren · Feb 12, 2013

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)