1. 程式人生 > >使用bcryptjs對密碼加密時,其校驗原理是怎樣的?

使用bcryptjs對密碼加密時,其校驗原理是怎樣的?

Question

剛開始接觸這種加密方式,而又對加密原理不瞭解時,很容易產生這種疑問❔:

對一個密碼,bcryptjs每次生成的hash都不一樣,那麼它是如何進行校驗的?

Basic verification

  1. 雖然對同一個密碼,每次生成的hash不一樣,但是hash中包含了salt(hash產生過程:先隨機生成salt,salt跟password進行hash);
  2. 在下次校驗時,從hash中取出salt,salt跟password進行hash;得到的結果跟儲存在DB中的hash進行比對,compareSync中已經實現了這一過程:bcrypt.compareSync(password, hashFromDB);

Let Code tell you

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!