BCrypt 加密 验证

微服务 BCrypt密码加密

1 BCrypt密码加密

1.1 前言

任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过哈希算法进行加密。有很多标准的算法比如SHA

或者MD5,结合salt(盐)是一个不错的选择。 Spring Security提供了BCryptPasswordEncoder类,实现Spring的

PasswordEncoder接口使用BCrypt强哈希方法来加密密码。

BCrypt强哈希方法 每次加密的结果都不一样。

1.2 boot -user 引入项目依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐security</artifactId>
</dependency>
1.3添加配置类

在添加spingsecurity依赖后,所有的地址都被SpringSecurity所控制,我们暂时只需要使用到BCrypt的密码加密部分,所以我们要添加配置类,让所有的地址都能够匿名访问。

package com.liu.user.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;

/**
 *  让所有的连接都能够被访问,所有的请求都是被认真,关闭csrf
 */
@Configuration
@EnableWebSecurity
public class WebSecurtyConfig extends WebSecurityConfigurerAdapter{


    @Override
    protected void configure(HttpSecurity http) throws Exception {
               http
                   .authorizeRequests().antMatchers("/**").permitAll()
                   .anyRequest().authenticated()
                   .and().csrf().disable();
    }
}




1.4 添加到容器中

添加BCryptPasswordEncoder 的声明,这样我们需要的密码加密类,就放到注册到容器里了

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return  new BCryptPasswordEncoder();
    }
1.5 加密

 public void addUser(User user, String code) {

            String syscode = (String) redisTemplate.boundHashOps(RedisKeyEnum.CAPTCHA_CODE.getKey()).get(user.getMobile());
            if (syscode ==null){
                throw new RuntimeException("请点击获取短信验证码");
            }
             if(!syscode.equals(code)){
                throw  new RuntimeException("您输入的验证码不正确,请确认后重新输入");
             }
             user.setId(idWorker.nextId()+"");

             user.setPassword(encoder.encode(user.getPassword()));
             userDao.save(user);


        }

1.6 密码验证
 public User findByMobileAndPassword(String mobile,String password){
            User  user = userDao.findByMobile(mobile);
            if(user!=null && encoder.matches(password,user.getPassword())){
                return  user;

            }else {
                return  null;
            }
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值