A place to hold mainly reading notes, and some technical stuff occasionally. 这里主要是一些读书笔记、感悟;还有部分技术相关的内容。
目录[-]
刚开始接触这种加密方式,而又对加密原理不了解时,很容易产生这种疑问❔:
对一个密码,bcryptjs每次生成的hash都不一样,那么它是如何进行校验的?
bcrypt.compareSync(password, hashFromDB);
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
If you have any questions or any bugs are found, please feel free to contact me.
Your comments and suggestions are welcome!