使用Spring Security下的BCryptPasswordEncoder进行密码加密

以往一般都用MD5加盐进行密码加密, 现在正好使用Spring Security安全框架, 那么就来了解一下如何使用 BCryptPasswordEncoder进行密码加密。

一. BCryptPasswordEncoder源码的大致理解

public class BCryptPasswordEncoder implements PasswordEncoder

public interface PasswordEncoder {
    String encode(CharSequence var1);
    boolean matches(CharSequence var1, String var2);
}

BCryptPasswordEncoder实现了PasswordEncoder接口,需要实现其加密和密码匹配的方法。

  public BCryptPasswordEncoder() {
        this(-1);
  }

  public BCryptPasswordEncoder(int strength) {
        this(strength, (SecureRandom)null);
  }
  public BCryptPasswordEncoder(int strength, SecureRandom random) {
        this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
        this.logger = LogFactory.getLog(this.getClass());
        this.strength = strength;
        this.random = random;
    }

    public String encode(CharSequence rawPassword) {
        String salt;
        if (this.strength > 0) {
            if (this.random != null) {
                salt = BCrypt.gensalt(this.strength, this.random);
            } else {
                salt = BCrypt.gensalt(this.strength);
            }
        } else {
            salt = BCrypt.gensalt();
        }
        return BCrypt.hashpw(rawPassword.toString(), salt);
    }

    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (encodedPassword != null && encodedPassword.length() != 0) {
            if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
                this.logger.warn("Encoded password does not look like BCrypt");
                return false;
            } else {
                return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
            }
        } else {
            this.logger.warn("Empty encoded password");
            return false;
        }
    }

使用SecureRandom生成的强(安全)随机数作为盐进行加密,不需要我们去记录这个盐,因为它会直接混在加密后的密码串中。
加密与匹配都是调用了BCrypt类中的方法。

二.具体使用

1.加密很简单,创建BCryptPasswordEncoder 类后调用其encode方法,把待加密的密码作为参数传进去得到加密后的密码,设置密码为加密后的密码再进行新增操作。

...
...
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// 加密
String encodedPassword = passwordEncoder.encode(user.getPassword().trim());
user.setPassword(encodedPassword);
...
...

2.在进行密码匹配时,如登陆操作,不用另外写匹配方法,在配置文件中进行配置即可,这里使用xml的形式进行配置。
(关于Spring Security配置文件的别的内容省略)
首先要配置BCryptPasswordEncoder这个Bean

 <beans:bean id="bCryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

接下去只要在认证管理器的用户认证中引用这个加密方式即可,在登陆时会自行进行密码匹配。
(用户认证:需要创建一个类实现UserDetailsService,实现其loadUserByUsername方法,会对用户名,密码,权限集等等进行判断)

    <!-- 认证管理器 -->
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder ref="bCryptEncoder"/>
        </authentication-provider>
    </authentication-manager>

数据库中加密后的密码串参考:
$2a$10$XLKswJdEFnyFRkVU4CmoPe1uX6roiDRPYhLOV3dI22/A/r1TVC36S


随意记录一下,省得我个猪脑不知道下回用的时候就忘了呢。

  • 8
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Spring Security是一个功能强大的安全框架,用于在Spring应用程序中实现身份验证和授权。BCryptPasswordEncoder是Spring Security提供的一种密码编码器,用于对用户密码进行加密和验证。 要配置BCryptPasswordEncoder,首先需要在Spring配置文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 然后,在Spring Security的配置类中进行配置。可以创建一个继承自WebSecurityConfigurerAdapter的类,并重写configure方法,如下所示: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin") .password(passwordEncoder().encode("admin123")) .roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 上述代码中,configure方法用于配置用户认证信息,使用inMemoryAuthentication将用户名、密码和角色存储在内存中。configure方法还配置了URL的访问权限,只有具有ADMIN角色的用户才能访问/admin/**路径下的资源。 最后,通过@Bean注解创建一个BCryptPasswordEncoder的实例,供其他地方使用
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值