Skip to main content
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";

// 使用 argon2 (默认)
const argonHash = await Bun.password.hash(password, {
  memoryCost: 4, // 内存使用量(千字节)
  timeCost: 3, // 迭代次数
});

Bun 还实现了 bcrypt 算法。指定 algorithm: "bcrypt" 来使用它。
// 使用 bcrypt
const bcryptHash = await Bun.password.hash(password, {
  algorithm: "bcrypt",
  cost: 4, // 介于 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 > 哈希 获取完整文档。