BCryptPasswordEncoder

BCryptPasswordEncoder 是一种使用 BCrypt 加密算法来加密密码的方法。它是在 Spring Security 中用来加密用户密码的一个类,其目的是为了防止密码被明文存储在数据库中。BCrypt 是一种强哈希算法,它能很好地防止被暴力破解。采用SHA-256 +随机盐+密钥对密码进行加密

首先导入依赖

<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>5.7.6</version>
        </dependency>

编写配置类

package com.qingyun.kunba.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.security.SecureRandom;

@Data
@Configuration
@ConfigurationProperties(prefix = "encoder.crypt")
public class PasswordConfig {
    /**
     * 加密强度
     */
    private int strength;
    /**
     * 干扰因子
     */
    private String secret;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        //System.out.println("secret = " + secret);
        //对干扰因子加密
        SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        //对密码加密
        return new BCryptPasswordEncoder(strength, secureRandom);
    }
}

配置yml

encoder:
  crypt:
    secret: ${random.uuid} # 随机的密钥,使用uuid
    strength: 6 # 加密强度4~31,决定盐加密时的运算强度,超过10以后加密耗时会显著增加

接着就可以测试了

@Autowired
private BCryptPasswordEncoder encoder;


@Test
    void savePassword() {
        // encode():对明文字符串进行加密
        //注册用户时,使用SHA-256+随机盐+密钥把用户输入的密码进行hash处理,得到密码的hash值,然后将其存入数据库中。
        String pw = encoder.encode("abcd");
        System.out.println(pw);

        // matches():对加密前和加密后是否匹配进行验证
        //用户登录时,密码匹配阶段并没有进行密码解密(因为密码经过Hash处理,是不可逆的),
        // 而是使用相同的算法把用户输入的密码进行hash处理,得到密码的hash值,然后将其与从数据库中查询到的密码hash值进行比较。
        // 如果两者相同,说明用户输入的密码正确。
        System.out.println(encoder.matches("asdsad", pw));
        System.out.println(encoder.matches("abcd", pw));


    }

测试结果如下

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天辰尽落

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值