0

我在 Spring Security 的 Md4PasswordEncoder 中注意到以下代码:

/**
 * 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);
}

我目前正在开发自定义 PasswordEncoder。谁能解释一下为什么spring开发人员通过向传入的对象添加一个空字符串来处理null?

提前致谢

4

1 回答 1

1

我不认为这样做是出于特定原因。我认为这更多是因为开发人员不关心在以后的版本中对其进行更改。

在 3.0.3 版本之前,代码是这样的(源代码):

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    }

在这个版本中,如果encPass是 null 并且如果第 79 行的语句String pass1 = encPass;不是原来的,第 81 行会抛出一个NPE.

但是,在更高版本(您正在查看的版本)中,使用了PasswordEncoderUtils中的 equals ,它已经处理了encPass可能为空的情况。

因此,我认为"" +在当前版本中是多余的,并且没有特殊原因留在那里。(也许是因为它没有破坏任何东西,也不是造成重大性能损失的原因)

于 2012-12-11T16:03:27.707 回答