使用场景
大多数系统都需要保存用户的登录密码,但是不能进行明文保存,延伸方案就是进行“密码加密”。
MD5
密码直接进行加密不行,存在解密的风险,那么我们可以使用MD5进行指定的数据进行摘要,MD5正常情况是不能进行反解密的,不正常情况当然是通过暴力破解简单的密码也可以。
MD5+盐
salt是可以提高MD5的安全,如 密码+salt 进行MD5摘要
旧系统中salt一般会配置在配置文件
BCryptPasswordEncoder
在 Spring Security 中有一个加密的类 BCryptPasswordEncoder ,它的使用非常的简单而且也比较有趣,不需要单独配置salt也可。
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public void TestCrypt()
{
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String password = "123456";
String encode1 = bCryptPasswordEncoder.encode(password);
System.out.println("encode1:" + encode1);
String encode2 = bCryptPasswordEncoder.encode(password);
System.out.println("encode2:" + encode2);
System.out.print(encode1.equals(encode1));
}
//encode1:$2a$10$SqbQb0pD3KYrH7ZVTWdRZOhPAelQqa..lUnysXoWag6RvMkyC5SE6
//encode2:$2a$10$0sjBLlwrrch2EjgYls197e9dGRCMbQ7KUIt/ODPTSU0W.mEPaGkfG
//false
相同的密码通过两次加密结果是不一样的。
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public void TestCrypt()
{
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String encode1 = bCryptPasswordEncoder.encode(password);
System.out.println("encode1:" + encode1);
boolean matches1 = bCryptPasswordEncoder.matches(password, encode1);
System.out.println("matches1:" + matches1);
String encode2 = bCryptPasswordEncoder.encode(password);
System.out.println("encode2:" + encode2);
boolean matches2 = bCryptPasswordEncoder.matches(password, encode2);
System.out.println("matches2:" + matches2);
}
encode1:$2a$10$qxU.rFLeTmZg47FyqJlZwu.QNX9RpEvqBUJiwUvUE0p4ENR.EndfS
matches1:true
encode2:$2a$10$NyGEOsQ1Hxv2gvYRmaEENueORlVDtSqoB/fHN76KkvQDeg7fbTy22
matches2:true
调用matches方法进行匹配时有可以匹配上。
大致原理为:在生成的摘要中存在固定位置的salt,可以通过再次加密方法分析salt进行加密后的数据进行比较。
本文介绍了如何在系统中使用MD5和BCryptPasswordEncoder进行密码加密,特别是BCryptPasswordEncoder在SpringSecurity中的应用,强调了盐的概念以及其如何增强密码安全性。同时,提到相同的密码经过BCryptPasswordEncoder加密后会得到不同的结果,便于验证和增加破解难度。
2万+

被折叠的 条评论
为什么被折叠?



