Spring Security安全框架中BCrypt强哈希加密算法使用

文章不包含认证机制。
任何应用考虑到安全,绝不能明文的方式保存密码密码应该通过某种方式进行加密。
如今已有很多标准的算法比如SHA或者MD5再结合salt(盐)使用是一个不错的选择。
废话不多说!直接开始
SpringBoot 中提供了Spring Security
BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密密码

第一步:pom导入依赖:

<dependency>
     <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐security</artifactId>
</dependency>

注意:Spring Security认的是拦截所有路径,但是只是需要它的加密算法,所以我们要添加一个配置类,让所有地址可以匿名访问

Spring Security 安全配置类 *.config

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Spring Security安全配置类
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    /**
         * authorizeRequests() 是所有security全注解配置实现的开端,表示开始说明需要的权限。
         * 需要的权限分两部分,第一部分是拦截的路径,第二部分访问该路径需要的权限。
         * antMatchers是表示拦截什么路径,permitAll()任何权限都可以访问,就是直接放行所有。
         * anyRequest()任何的请求,authenticated 认证后才能访问。
         * .and().csrf().disable(); 固定写法,表示使csrf拦击失效(csrf 是网络攻击技术。有想了解自己找资料)。
         */
        http
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }
}


在springboot 启动类中添加配置BCryptPasswordEncoder

@Bean
public BCryptPasswordEncoder bcryptPasswordEncoder(){
    return new BCryptPasswordEncoder();
}

如果没有配置 BCryptPasswordEncoder 也就是没有在容器中,springboot没法管理它

第二步:使用
我用的是spring全家桶开发的,所以操作数据库是:Spring Data Jpa

@Autowired //注入BCryptPasswordEncoder
BCryptPasswordEncoder encoder;

public void deyadd(Admin admin) {
    //密码加密 encoder.encode(需要加密的密码
    String newpassword = encoder.encode(admin.getpassword());//加密后的密码
    
    admin.setPassword(newpassword);
    adminDao.save(admin);
}

密码验证:

public Addmin deyPassword(String loginname,String password){
    //查询数据库中的密码
    Addmin addmin = adminDao.findByLoginname(loginname);
    //密码验证 encoder.matches(输入的密码数据库中的密码
    if( addmin!=null && encoder.matches(password,admin.getpassword())){
        return addmin;
    {
    else{
        return null;
    }
}

到此密码加密就完成了。

文章不包含认证机制。
————————————————
版权声明:本文为CSDN博主「常家壮」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44257023/article/details/103008530

相关文章

背景:计算机内部用补码表示二进制数。符号位1表示负数,0表...
大家好,我们现在来讲解关于加密方面的知识,说到加密我认为不...
相信大家在大学的《算法与数据结构》里面都学过快速排序(Qui...
加密在编程中的应用的是非常广泛的,尤其是在各种网络协议之...
前言我的目标是写一个非常详细的关于diff的干货,所以本文有...
对称加密算法 所有的对称加密都有一个共同的特点:加密和...