BCrypt 密码散列

BCrypt 简介

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

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

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

BCrypt 使用

  1. 引入依赖
      <dependency><groupId>org.springframework.securitygroupId><artifactId>spring-security-cryptoartifactId><version>5.2.2.RELEASEversion>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;@Beanpublic 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 {@Autowiredprivate BCryptPasswordEncoder encoder;@Testpublic 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);}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部