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 > Hashing。