密码哈希
使用 Bun.password.hash() 安全地对密码进行哈希处理。它内置于 Bun 中,无需第三方依赖。
TypeScript
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/...
默认情况下,Bun.password.hash() 使用 Argon2id 算法。传入第二个参数即可使用其他算法或配置哈希参数。
TypeScript
const password = "super-secure-pa$$word";
// 使用 argon2(默认)
const argonHash = await Bun.password.hash(password, {
algorithm: "argon2id",
memoryCost: 8, // 内存使用量,单位为 kibibytes(最小值 8)
timeCost: 3, // 迭代次数
});
Bun 还实现了 bcrypt 算法。指定 algorithm: "bcrypt" 即可使用。
TypeScript
// 使用 bcrypt
const bcryptHash = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 4, // 数值范围为 4-31
});
使用 Bun.password.verify() 验证密码。哈希值中存储了算法及其参数,因此无需再次指定。
TypeScript
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);
const isMatch = await Bun.password.verify(password, hash);
// => true
请参阅 Bun.password。