推荐链接:
总结——》【Java】
总结——》【Mysql】
总结——》【Spring】
总结——》【SpringBoot】
总结——》【MyBatis、MyBatis-Plus】
Spring——》SpringSecurity中的BCryptPasswordEncoder算法
一、简介
SHA系列是Hash算法,不是加密算法。
加密算法:可以解密(这个与编码/解码一样)
Hash算法:不可解密(过程不可逆)
SpringSecurity中的BCryptPasswordEncoder方法采用SHA-256 +随机盐+密钥对密码进行加密。
(1)加密(encode)
注册用户时,使用SHA-256+随机盐+密钥把用户输入的密码进行hash处理,得到密码的hash值,然后将其存入数据库中。
(2)密码匹配(matches)
用户登录时,密码匹配阶段并没有进行密码解密(因为密码经过Hash处理,是不可逆的),而是使用相同的算法把用户输入的密码进行hash处理,得到密码的hash值,然后将其与从数据库中查询到的密码hash值进行比较。如果两者相同,说明用户输入的密码正确。
Q:为什么处理密码时要用hash算法,而不用加密算法?
A:因为hash算法是不可逆的,即使数据库泄漏,黑客也很难破解密码。
Q:既然这种加密方式是不可逆的,那么当用户忘记密码后呢?后台管理也查看不到密码。
A:现在为了用户的信息安全,实际上是做到连后台管理员都无法直接看到用户的密码信息。现在大多数系统都是绑定手机或者邮箱之类的,当用户忘记密码后都是通过手机验证码或者邮箱的形式让用户重置密码,并不能够直接找系统管理员获取到密码。
二、导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-crypto -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>5.6.2</version>
</dependency>
三、代码示例
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class Test {
final static private String password = "123456";
public static void main(String[] args) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// encode():对明文字符串进行加密
String encode1 = encoder.encode(password);
System.out.println("encode1:" + encode1);
String encode2 = encoder.encode(password);
System.out.println("encode2:" + encode2);
// matches():对加密前和加密后是否匹配进行验证
boolean matches1 = encoder.matches(password, encode1);
System.out.println("matches1:" + matches1);
boolean matches2 = encoder.matches(password, encode2);
System.out.println("matches2:" + matches2);
}
}
四、源码解析
1、encode()相关
(1)方法调用过程
(2)关键代码
// 获得真正的salt
real_salt = salt.substring(off + 3, off + 25);
// 使用 base64 进行解码
saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
// passwordb + saltb
hashed = B.crypt_raw(passwordb, saltb, rounds, minor == 'x', minor == 'a' ? 0x10000 : 0);
// 对 salt 进行 base64 编码后放入了 rs 中
encode_base64(saltb, saltb.length, rs);
// 对 hashed 进行 base64 编码后也放入了 rs 中
encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1, rs);
2、matchs()相关
(1)方法调用过程
(2)关键代码
// plaintext :我们的密码,即 “123456”, hashed :加密后的密码
// hashpw():和加密时的方法一致(会从hashed里提取真正的salt)
equalsNoEarlyReturn(hashed, hashpw(plaintext, hashed));
五、总结
encode():同样的密码可以生成不同的密文(密文中包含salt和hash)
matches():进行匹配验证
因为每次的 salt 不同,因此每次的 hash 也不同。这样就可以使得相同的 明文 生成不同的 密文。
而密文中包含 salt 和 hash,因此验证过程和生成过程也是相同的。