版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/t1g2q3/article/details/86542837
- Spring Security中的BCryptPasswordEncoder方法采用SHA-256 +随机盐+密钥对密码进行加密。SHA系列是Hash算法,不是加密算法,使用加密算法意味着可以解密(这个与编码/解码一样),但是采用Hash处理,其过程是不可逆的。
- (1)加密(encode):注册用户时,使用SHA-256+随机盐+密钥把用户输入的密码进行hash处理,得到密码的hash值,然后将其存入数据库中。
- (2)密码匹配(matches):用户登录时,密码匹配阶段并没有进行密码解密(因为密码经过Hash处理,是不可逆的),而是使用相同的算法把用户输入的密码进行hash处理,得到密码的hash值,然后将其与从数据库中查询到的密码hash值进行比较。如果两者相同,说明用户输入的密码正确。
- 这正是为什么处理密码时要用hash算法,而不用加密算法。因为这样处理即使数据库泄漏,黑客也很难破解密码(破解密码只能用彩虹表)。
- 从bcryptjs实现快速理解:
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