Bun

指南工具程式

使用 Bun 雜湊處理密碼

Bun.password.hash() 函數提供了一個快速、內建的機制,可在 Bun 中安全地雜湊處理密碼。無需任何第三方依賴。

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/...

預設情況下,這會使用 Argon2id 演算法。傳遞第二個參數給 Bun.password.hash() 以使用不同的演算法或配置雜湊參數。

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

// use argon2 (default)
const argonHash = await Bun.password.hash(password, {
  memoryCost: 4, // memory usage in kibibytes
  timeCost: 3, // the number of iterations
});

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

// use bcrypt
const bcryptHash = await Bun.password.hash(password, {
  algorithm: "bcrypt",
  cost: 4, // number between 4-31
});

使用 Bun.password.verify() 來驗證密碼。演算法及其參數儲存在雜湊值本身中,因此無需重新指定配置。

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

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

請參閱 文件 > API > 雜湊處理 以取得完整文件。