Bun.password.hash() 函數提供了一個快速、內置的安全哈希密碼機制。不需要第三方依賴。
ts
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() 以使用不同的算法或配置哈希參數。
ts
const password = "super-secure-pa$$word";
// 使用 argon2(默認)
const argonHash = await Bun.password.hash(password, {
memoryCost: 4, // 內存使用量(KiB)
timeCost: 3, // 迭代次數
});Bun 還實現了 bcrypt 算法。指定 algorithm: "bcrypt" 來使用它。
ts
// 使用 bcrypt
const bcryptHash = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 4, // 4-31 之間的數字
});使用 Bun.password.verify() 驗證密碼。算法及其參數存儲在哈希本身中,因此無需重新指定配置。
ts
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);
const isMatch = await Bun.password.verify(password, hash);
// => true請參閱 文檔 > API > Hashing 獲取完整文檔。