執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

密碼雜湊

使用 Bun.password.hash() 安全地對密碼進行雜湊處理。它內置於 Bun 中,無需第三方相依。

TypeScript
const password = "super-secure-pa$$word";

const hash = await Bun.password.hash(password);
// => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh6E8DQRhEXg/M/...

預設情況下,Bun.password.hash() 使用 Argon2id 演算法。傳入第二個引數即可使用其他演算法或設定雜湊引數。

TypeScript
const password = "super-secure-pa$$word";

// 使用 argon2(預設)
const argonHash = await Bun.password.hash(password, {
  algorithm: "argon2id",
  memoryCost: 8, // 記憶體使用量,單位為 kibibytes(最小值 8)
  timeCost: 3, // 迭代次數
});

Bun 還實現了 bcrypt 演算法。指定 algorithm: "bcrypt" 即可使用。

TypeScript
// 使用 bcrypt
const bcryptHash = await Bun.password.hash(password, {
  algorithm: "bcrypt",
  cost: 4, // 數值範圍為 4-31
});

使用 Bun.password.verify() 驗證密碼。雜湊值中儲存了演算法及其引數,因此無需再次指定。

TypeScript
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);

const isMatch = await Bun.password.verify(password, hash);
// => true

請參閱 Bun.password。