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' ? "\000" : "")).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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM