SpringSecurity BCryptPasswordEncoder

    public BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion version, int strength, SecureRandom random) {
    
    
        this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2(a|y|b)?\\$(\\d\\d)\\$[./0-9A-Za-z]{53}");
        this.logger = LogFactory.getLog(this.getClass());
        if (strength == -1 || strength >= 4 && strength <= 31) {
    
    
            this.version = version;
            this.strength = strength == -1 ? 10 : strength;
            this.random = random;
        } else {
    
    
            throw new IllegalArgumentException("Bad strength");
        }
    }

使用默认强度是10

    public String encode(CharSequence rawPassword) {
    
    
        if (rawPassword == null) {
    
    
            throw new IllegalArgumentException("rawPassword cannot be null");
        } else {
    
    
            String salt;
            if (this.random != null) {
    
    
                salt = BCrypt.gensalt(this.version.getVersion(), this.strength, this.random);
            } else {
    
    
                salt = BCrypt.gensalt(this.version.getVersion(), this.strength);
            }

            return BCrypt.hashpw(rawPassword.toString(), salt);
        }
    }

使用随机盐进行加密,即使明文的密码相同,最终加密的结果也可能不同

package claroja.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@SpringBootTest
public class DemoApplicationTests {
    
    

    @Test
    void contextLoads() {
    
    
        PasswordEncoder pw = new BCryptPasswordEncoder();
        //每次加密的结果可能不同
        String encode = pw.encode("123");
        System.out.println(encode);
        //比较密码,springsecurit能记录每次随机的盐值
        boolean matches = pw.matches("123", encode);
        System.out.println(matches);
    }

}

猜你喜欢

转载自blog.csdn.net/claroja/article/details/114340287