Featured image of post NodeJS 上實作 Hash 與 Salt

NodeJS 上實作 Hash 與 Salt

Hash 在記錄使用者密碼很常被使用

Hash

  • 不可逆
  • 會被彩虹表破解
  • 可用來驗證檔案正確性

Salt (加鹽)

  • 類似加一把鑰匙的意思
  • 常常使用在密碼的情境中
  • 每個使用者的 salt 都要不一樣
  • bcrypt 的 hash 的前半段就是代表 salt
  • 比較密碼是否正確時要有使用者之前的 salt,才能比較出正確 hash

安裝

1
npm install bcrypt

實作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import bcrypto from "bcrypt";

export async function createHash(input) {
  //產生salt,10代表計算數字,越大所耗費運算資源越大
  const genSalt = await bcrypto.genSalt(10);

  //使用salt+內文產生hash
  const hashed1 = await bcrypto.hash(input, genSalt);

  //也可以將hash與salt合併一起,直接在第二個參數帶入代表運算salt的round的integer
  const hashed2 = await bcrypto.hash(input, 10);
  return hashed1;
}

export async function compareHash(plainText, hash) {
  //由於hash內就帶有salt資訊所以,直接將內文與hash做compare,若是正確就回傳true
  const result = await bcrypto.compare(plainText, hash);
  return result;
}

參考

dinostack.cc
使用 Hugo 建立
主題 StackJimmy 設計