crypto.argon2(algorithm, parameters, callback)


稳定性: 1.2 - 发布候选版

  • algorithm <string> Argon2 的变体,可以是 "argon2d""argon2i""argon2id" 之一。
  • parameters <Object>
    • message <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> 必需,这是用于 Argon2 密码哈希应用的密码。
    • nonce <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> 必填,长度至少为8字节。这是用于Argon2密码哈希应用的盐值。
    • parallelism <number> 必需,流水线的并行度决定了可以运行多少条计算链(通道)。必须至少为 1,最多为 2**24-1
    • tagLength <number> 必填,要生成的密钥长度。长度必须至少为 4,且最多为 2**32-1
    • memory <number> 必需的,以1KiB块为单位的内存成本。必须至少为 8 * parallelism,最多为 2**32-1。实际块数会向下舍入到最接近的 4 * parallelism 倍数。
    • passes <number> 必填,传递次数(迭代次数)。最少必须为 1,最多为 2**32-1
    • secret <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <undefined> 可选的,随机附加输入,类似于盐值,不应与派生密钥一起存储。在密码哈希应用中,这被称为胡椒。如果使用,长度不得超过 2**32-1 字节。
    • associatedData <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <undefined> 可选,要添加到哈希的附加数据,功能上等同于盐或密钥,但用于非随机数据。如果使用,长度不得超过 2**32-1 字节。
  • callback <Function>

提供异步 氩气2 实现。Argon2 是一种基于密码的密钥派生函数,旨在在计算和内存方面消耗较大,以使暴力破解攻击不划算。

🌐 Provides an asynchronous Argon2 implementation. Argon2 is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.

nonce 应尽可能唯一。建议 nonce 是随机的,并且至少 16 字节长。详情请参见 NIST SP 800-132

🌐 The nonce should be as unique as possible. It is recommended that a nonce is random and at least 16 bytes long. See NIST SP 800-132 for details.

在为 messagenoncesecretassociatedData 传递字符串时,请考虑 将字符串用作加密 API 输入时的注意事项

🌐 When passing strings for message, nonce, secret or associatedData, please consider caveats when using strings as inputs to cryptographic APIs.

callback 函数会传入两个参数:errderivedKey。当密钥派生失败时,err 是一个异常对象,否则 errnullderivedKey 作为 Buffer 传递给回调函数。

🌐 The callback function is called with two arguments: err and derivedKey. err is an exception object when key derivation fails, otherwise err is null. derivedKey is passed to the callback as a Buffer.

当任何输入参数指定无效的值或类型时,会抛出异常。

🌐 An exception is thrown when any of the input arguments specify invalid values or types.

const { argon2, randomBytes } = await import('node:crypto');

const parameters = {
  message: 'password',
  nonce: randomBytes(16),
  parallelism: 4,
  tagLength: 64,
  memory: 65536,
  passes: 3,
};

argon2('argon2id', parameters, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // 'af91dad...9520f15'
});const { argon2, randomBytes } = require('node:crypto');

const parameters = {
  message: 'password',
  nonce: randomBytes(16),
  parallelism: 4,
  tagLength: 64,
  memory: 65536,
  passes: 3,
};

argon2('argon2id', parameters, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // 'af91dad...9520f15'
});