user1668302
user1668302

Reputation: 157

Java Spring Security PasswordEncoder

I noticed following code in Md4PasswordEncoder in Spring Security:

/**
 * Takes a previously encoded password and compares it with a raw password after mixing in the salt and
 * encoding that value.
 *
 * @param encPass previously encoded password
 * @param rawPass plain text password
 * @param salt salt to mix into password
 * @return true or false
 */
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
    String pass1 = "" + encPass;
    String pass2 = encodePassword(rawPass, salt);
    return PasswordEncoderUtils.equals(pass1,pass2);
}

I'm currently working on developing custom PasswordEncoder. Could please anyone explain why are spring developers handling null by adding an empty string to the passed in object?

Thanks in advance

Upvotes: 0

Views: 472

Answers (1)

TJ-
TJ-

Reputation: 14363

I don't think this was done for a specific reason. I think it is more because the developers didn't care to change it over the later versions.

Until version 3.0.3, this is how the code used to look like (Source) :

78    public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
79        String pass1 = "" + encPass;
80        String pass2 = encodePassword(rawPass, salt);
81        return pass1.equals(pass2);
82    }

In this version, if encPass was null and if the statement on line 79 would have been String pass1 = encPass; instead of what it is, line 81 would have thrown a NPE.

However, in the later version (the one which you are looking at) equals from PasswordEncoderUtils has been used which already takes care of cases where encPass could be null.

Hence, I think "" + is redundant in the current version and was left there for no special reason. (Perhaps because it is not breaking anything and is not a reason for a significant performance loss)

Upvotes: 1

Related Questions