BCryptPasswordEncoder 加密
Spring Security中的BCryptPasswordEncoder方法采用SHA-256 +随机盐+**对密码进行加密。SHA系列是Hash算法,不是加密算法,使用加密算法意味着可以解密(这个与编码/解码一样),但是采用Hash处理,其过程是不可逆的。
传统的MD5加密
传统的md5 ,虽然是不可逆算法,但是还是有很大的方法获取原密码
虽然方法并不可靠(超大容量,存储md5密文和对应的结果),但是存在风险
后来出现了加盐的操作
给原文加入盐生成新的MD5值。
但是每次算出的 md5值都一样,这样非常不安全
从上图可见,值没有发生变化
故此,md5 加盐也会变的不那么可靠, 所以我找了 Bcrypt 相关的资料
PasswordEncoder 接口提供了俩个抽象方法.分别是 加密 encode & 密码匹配 matches
(1)加密(encode):注册用户时,使用SHA-256+随机盐+**把用户输入的密码进行hash处理,得到密码的hash值,然后将其存入数据库中。
(2)密码匹配(matches):用户登录时,密码匹配阶段并没有进行密码解密(因为密码经过Hash处理,是不可逆的),而是使用相同的算法把用户输入的密码进行hash处理,得到密码的hash值,然后将其与从数据库中查询到的密码hash值进行比较。如果两者相同,说明用户输入的密码正确。
bcrypt 的实现代码理解
const bcrypt = require('bcryptjs');
const password = "123";
// Step1: Generate Hash
// salt is different everytime, and so is hash
let salt = bcrypt.genSaltSync(10);// 10 is by default
console.log(salt);//$2a$10$TnJ1bdJ3JIzGZC/jVS.v3e
let hash = bcrypt.hashSync(password, salt); // salt is inclued in generated hash
console.log(hash);//$2a$10$TnJ1bdJ3JIzGZC/jVS.v3eXlr3ns0hDxeRtlia0CPQfLJVaRCWJVS
// Step2: Verify Password
// when verify the password, get the salt from hash, and hashed again with password
let saltFromHash = hash.substr(0, 29);
console.log(saltFromHash);//$2a$10$TnJ1bdJ3JIzGZC/jVS.v3e
let newHash = bcrypt.hashSync(password, saltFromHash);
console.log(newHash);//$2a$10$TnJ1bdJ3JIzGZC/jVS.v3eXlr3ns0hDxeRtlia0CPQfLJVaRCWJVS
console.log(hash === newHash); //true
// back end compare
console.log(bcrypt.compareSync(password, hash)); //true
PasswordEncoder实现类——BCryptPasswordEncoder
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.security.crypto.bcrypt;
import java.security.SecureRandom;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
public class BCryptPasswordEncoder implements PasswordEncoder {
private Pattern BCRYPT_PATTERN;
private final Log logger;
private final int strength;
private final SecureRandom random;
//构造函数用于设置不同的加密过程
public BCryptPasswordEncoder() {
this(-1);
}
public BCryptPasswordEncoder(int strength) {
this(strength, (SecureRandom)null);
}
public BCryptPasswordEncoder(int strength, SecureRandom random) {
this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
this.logger = LogFactory.getLog(this.getClass());
if (strength == -1 || strength >= 4 && strength <= 31) {
this.strength = strength;
this.random = random;
} else {
throw new IllegalArgumentException("Bad strength");
}
}
/*
*加密密码具体实现
*/
public String encode(CharSequence rawPassword) {
String salt;
if (this.strength > 0) {
if (this.random != null) {
salt = BCrypt.gensalt(this.strength, this.random);
} else {
salt = BCrypt.gensalt(this.strength);
}
} else {
salt = BCrypt.gensalt();
}
return BCrypt.hashpw(rawPassword.toString(), salt);
}
/*
*匹配密码具体实现
*/
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword != null && encodedPassword.length() != 0) {
if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
this.logger.warn("Encoded password does not look like BCrypt");
return false;
} else {
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
} else {
this.logger.warn("Empty encoded password");
return false;
}
}
}
在 spring secrity 中使用 bcrypt 加密算法
在配置类中 配置一个 PasswordEncoder Bean
//采用bcrypt对密码进行编码
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
test效果如下
@Test
public void testBcryptTest(){
//加密对象
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = "123456"; //用户密码
//循环5次
for (int i = 0; i < 5; i++) {
//每次密码都不一样
String encodePassword = passwordEncoder.encode(password);
System.out.println(encodePassword);
//但是效验是通过的
System.out.println(passwordEncoder.matches(password, encodePassword));
}
打印结果
$2a$10$YUthO3FOocQFxBgMMke2ROV2MKqAJwHEb8VeVhgcy4oZkx5S/zTHm
true
$2a$10$GGzTRQiEP6/vGrsCTi/FeelN6DLtXn87ieWPXXc2GZgtT5np9DF8i
true
$2a$10$tbH0BfD8Zw1iOonIpZlTOunUbc6C/D/DEbw0daEmtihAx19B61PzS
true
$2a$10$e1.3UWoXkX.0R4XhiCnBiunO7Ln0HHdDqGXbb2jH2fwZTadqGHYVW
true
$2a$10$fzDWX.RtTKXhr3z9PDra5e/ZHZMAHD/TxLleVSzC.BFWEvxIKTKN.
true