BCrypt密码加密教程(基于SpringBoot框架中spring security)简单入门教学

1.密码加密的作用

任何一个网站或应用的用户数据都是十分重要的,我们不可能用明文来保存在数据库中。因为如果我们的数据库被拖库后那么用户的数据就全部暴露了,这对企业来说是十分巨大的损失。密码应该通过哈希算法进行加密。

2.BCrypt加密

Spring Security提供了BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强
哈希方法来加密密码。
BCrypt强哈希方法 每次加密的结果都不一样

2.1 导入坐标

我的父工程SpringBoot坐标

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/>
    </parent>

Spring Security坐标,我是放在子模块下

	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-security</artifactId>
	</dependency>
2.2 添加配置类

Spring Security是一个强大的安全框架,BCrypt密码加密功能只是其中一小功能。
当我们引入了Spring Security后,我们的所有地址都被Spring Security拦截下来了,但是我们目前只用到了BCrypt密码加密功能,所以我们要放开对所有地址的拦截。(不知道这里这么写对不对)

创建WebSecurityConfig 类

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

向Spring容器中注入BCryptPasswordEncoder 类,修改SpringBoot启动类

	@Bean
	public BCryptPasswordEncoder encode(){
		return new BCryptPasswordEncoder();
	}
2.3 使用BCrypt

在需要使用加密的类中装载BCryptPasswordEncoder 类

	@Autowired
	private BCryptPasswordEncoder encode;

加密

加密后字段 encode.encode(需要加密字段)

向encode方法中传入需要加密的字段,放回一个加密后的字段,都是String类型

匹配(解密)

boolean encode.matches(需要验证的字段,加密字段)

因为每次使用BCrypt加密的字段是不一样的,所以要使用matches方法,该方法的第一个参数是需要验证的字段(也就是登录时候的密码),第二个参数是加密字段(也就是存储在数据库中的经过encode方法加密后的字段)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值