1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > BCrypt 密码散列

BCrypt 密码散列

时间:2022-02-12 02:57:03

相关推荐

BCrypt 密码散列

BCrypt 简介

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

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

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

BCrypt 使用

引入依赖

<dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-crypto</artifactId><version>5.2.2.RELEASE</version></dependency>

配置类

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import java.security.SecureRandom;@Configurationpublic 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);}}

加密,解密

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);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。