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 > 雜湊 以取得完整的說明文件。