GeekySelene
GeekySelene

Reputation: 927

How to check whether a password is BCrypt encoded or not in java

Im getting a user object bonded in a POST request to a Spring controller. In that object there is a password field. I want t check that filed whether its BCrypt encoded or not because the save and update both events are mapped to the same controller. Any idea how is this possible?

code snippet :

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveUser(Model model, @Validated @ModelAttribute("user") SystemUser user, BindingResult result) {

}

Upvotes: 3

Views: 2495

Answers (3)

vinceseguin
vinceseguin

Reputation: 91

According BCryptPasswordEncoder class from Spring, you could check if a String is encoded or not using this regex pattern

Pattern BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");

if (BCRYPT_PATTERN.matcher(stringToCheck).matches()) {
    // stringToCheck is an encoded bcrypt password.
}

Upvotes: 3

Shaun the Sheep
Shaun the Sheep

Reputation: 22742

Not quite sure what you're asking, but you can check relatively easily whether a string "looks like" a bcrypt password, since they have a distinctive format (e.g. $2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i).

So if your string starts with $2 followed by an a or b (you can usually ignore other cases), another $, a two-digit cost parameter and another $ then it's likely a bcrypt hash. Of course bcrypt hashes will also be valid plaintext passwords on many systems, but it's an unlikely choice (you can always reject passwords with this format).

It's also not clear from your question whether this value is always coming from the client - the client shouldn't be posting a bcrypt hash to the server though.

Upvotes: 0

vavasthi
vavasthi

Reputation: 952

It is hard to do. The way I have solved this problem in past is to have a very specific method for changePassword scenario. Once that is taken care of in a specific piece of code, the password is never updated with a regular save.

Upvotes: 1

Related Questions