spring security (BCryptPasswordEncoder)加密及判断密码是否相同

通过BCryptPasswordEncoder的加密的相同字符串的结果是不同的,如果需要判断是否是原来的密码,需要用它自带的方法。

加密:

  1. BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
  2. encode.encode(password);

判断:

需要通过自带的方法 matches 将未经过加密的密码和已经过加密的密码传进去进行判断,返回布尔值。

encode.matches(oldpassword,user1.getPassword());

举例说明:

  1. public class BCryptPasswordEncoderTest {
  2. public static void main(String[] args) {
  3. String pass = "admin";
  4. BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
  5. String hashPass = bcryptPasswordEncoder.encode(pass);
  6. System.out.println(hashPass);
  7. boolean f = bcryptPasswordEncoder.matches("admin",hashPass);
  8. System.out.println(f);
  9. }
  10. }

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

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

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

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

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

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

随机盐即为 AxafsyVqK51p.s9WAEYWYe

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

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

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

      </div>

原文地址:https://blog.csdn.net/qq_40741855/article/details/89358745

原文地址:https://www.cnblogs.com/jpfss/p/11010869.html