Skip to content

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 获取完整文档。

Bun学习网由www.bunjs.com.cn整理维护