BCrypt 密码散列

本文介绍了BCrypt不可逆加密算法的工作原理,如何使用随机盐增强安全性,并展示了如何在Spring Security中配置和使用BCryptPasswordEncoder进行密码加密和解密。通过实例演示了配置过程和测试代码。
摘要由CSDN通过智能技术生成

BCrypt 简介

BCrypt是一种不可逆的加密算法。使用随机盐,并将随机盐保存到密文中,不用单独存到数据库,更安全。

加密原理: hash( 密码 + 随机盐) * 加密次数。

使用BCrypt能实现每次加密的值都是不一样的,因为每次的随机盐都不同。

BCrypt 使用

  1. 引入依赖
      <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-crypto</artifactId>
        <version>5.2.2.RELEASE</version>
      </dependency>
  1. 配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.security.SecureRandom;

@Configuration
public class PasswordConfig {

    /**
     * 随机种子的长度
     */
    private int seedLength = 32;
    
    /**
     * 加密强度4~31,决定了密码和盐加密时的运算次数,超过10以后加密耗时会显著增加
     */
    private Integer strength = 10;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {

//      加密前度,数字越大强度越大,越安全,越耗时
        SecureRandom random = new SecureRandom(SecureRandom.getSeed(seedLength));
        return new BCryptPasswordEncoder(strength, random);
    }
}
  1. 加密,解密
package bcrypt;

import com.heima.admin.AdminApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = AdminApplication.class)
@RunWith(SpringRunner.class)
public class BCryptTest {

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Test
    public void test() {
        //--------加密---------
        //密码
        String password = "123456";
        //使用BCrypt进行加密
        String newPwd = encoder.encode(password);
        System.out.println("密文为:" + newPwd);

        //--------解密---------
        //使用BCrypt进行解密,传入 密码、密文
        boolean b = encoder.matches(password, newPwd);
        System.out.println("前后密码是否一致: " + b);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值