Question

My question is how can I check if a password is already crypted with Bcrypt.And if it is, let Bcrypt do nothing ,just leave the password like it is.I'm working with Java(EE),Spring.

public static String hashPassword(String userPassword) {
    String bCrypt = null;
    if (userPassword == null)
        throw new NullPointerException("Input password for hashing was null.");
    bCrypt = BCrypt.hashpw(userPassword, BCrypt.gensalt(12));
    return bCrypt;
}
Was it helpful?

Solution 2

Generally you should not just replace a string that can have any value like a password with another one. The problem is that somebody could enter a password that has the same format of your bcrypt output, and you would have no way of distinguishing the two.

Fortunately the output of your bcrypt function is a string that consist of a version, "salt rounds", the salt and the hash, surrounded by $ separator characters. So the best method of distinguishing the two is to write a regular expression that matches the following output (from the jBCrypt 0.3 source):

rs.append("$2");
if (minor >= 'a')
        rs.append(minor);
rs.append("$");
if (rounds < 10)
        rs.append("0");
rs.append(Integer.toString(rounds));
rs.append("$");
rs.append(encode_base64(saltb, saltb.length));
rs.append(encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1));
return rs.toString();

I would however much advice you to add a column to your database that indicates the hash algorithm used on the row, (if any).

OTHER TIPS

There is NO way to check if bcrypt algorithm has been applied, because one CAN create a password that ressembles a bcrypt coincidently, BUT you can use a trick: let the password not being allowed to have more than 40 chars, then check if the password is greater than such as 59 chars (or adjust better to your logic), thus you can deduce that the password has, or not, been bcrypted.

To know if the encoded password does look like BCrypt try this,

private Pattern BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
....
if (!BCRYPT_PATTERN.matcher(password).matches()){
    //do someting
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top