spring security 中解密时如何解密的?

4,114 阅读1分钟
[是无法将加密后的密文解密成明文只能通过 bcryptPasswordEncoder.matches("admin",hashPass);来比较密码是否正确]

参考来源:https://www.zhihu.com/question/54720851

spring security 中PasswordEncoder的加密是采用SHA-256+随机盐+密钥进行加密,那解密时如何解密的?

学习到这一块,查看了一些源码。以BCryptPasswordEncoder为例

public class BCryptPasswordEncoderTest {
    public static void main(String[] args) {
        String pass = "admin";
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String hashPass = bcryptPasswordEncoder.encode(pass);
        System.out.println(hashPass);

        boolean f = bcryptPasswordEncoder.matches("admin",hashPass);
        System.out.println(f);

    }
}

可以看到,每次输出的hashPass 都不一样,
但是最终的f都为 true,即匹配成功。

查看代码,可以看到,其实每次的随机盐,都保存在hashPass中。

在进行matchs进行比较时,调用BCrypt 的String hashpw(String password, String salt)

方法。两个参数即”admin“和 hashPass

//******BCrypt.java******salt即取出要比较的DB中的密码*******
real_salt = salt.substring(off + 3, off + 25);
try {
// ***************************************************
    passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8");
}
catch (UnsupportedEncodingException uee) {}
saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
B = new BCrypt();
hashed = B.crypt_raw(passwordb, saltb, rounds);

假定一次hashPass为:$2a$10$AxafsyVqK51p.s9WAEYWYeIY9TKEoG83LTEOSB3KUkoLtGsBKhCwe

随机盐即为 AxafsyVqK51p.s9WAEYWYe

(salt = BCrypt.gensalt();中有描述)

可见,随机盐(AxafsyVqK51p.s9WAEYWYe),会在比较的时候,重新被取出。

即,加密的hashPass中,前部分已经包含了盐信息。