密码加密存储

实际项目中我们不会把密码明文存储在数据库中

默认使用的PasswordEncoder要求数据库中的密码格式为:{id}password。它会根据id去判断密码的加密方式。但是我们一般不会采用这种方式。所以就需要替换PasswordEncoder

我们一般提供SpringSecurity为我们提供的BCryptPasswordEncoder

我们只需要把BCryptPasswordEncoder对象注入到Spring容器中,SpringSecurity就会使用该PasswordEncoder进行密码校验。

我们可以定义一个SpringSecurity的配置类,SpringSecurity要求这个类要继承WebSecurityConfigurerAdapter

注册时,要使用该对象进行加密,注入PasswordEncoder使用就可以

@Autowired
private PasswordEncoder passwordEncoder;

1.导入BCryptPasswordEncoder

package springsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 创建BCryptPasswordEncoder注入容器
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }



}

2.加密:注册时,对用户输入的密码加密,将加密的密码存入数据库

@Test
public void test(){
    BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
    // 加密:注册时,对用户输入的密码加密,将加密的密码存入数据库
    System.out.println(passwordEncoder.encode("1234"));
    System.out.println(passwordEncoder.encode("1234"));

    // 校验:判断用户输入的密码是否和数据中的密码是一致的
    System.out.println(passwordEncoder.matches("1234", "$2a$10$v7.Zhf0Px3iWZO8dbTR.MOLW3cR0trpHqGNUit0VefIvF2hlbZBa."));
}

3.校验:判断用户输入的密码是否和数据中的密码是一致的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值