crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)
password<string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>salt<string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>iterations<number>keylen<number>digest<string>callback<Function>
提供一个异步的基于密码的密钥派生函数 2(PBKDF2)实现。通过 digest 指定的 HMAC 摘要算法,用于从 password、salt 和 iterations 派生请求字节长度(keylen)的密钥。
【Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by digest is
applied to derive a key of the requested byte length (keylen) from the
password, salt and iterations.】
提供的 callback 函数会接收两个参数:err 和 derivedKey。如果在生成密钥时发生错误,err 将被设置;否则 err 将为 null。默认情况下,成功生成的 derivedKey 会作为 Buffer 传递给回调。如果任何输入参数指定了无效的值或类型,将会抛出错误。
【The supplied callback function is called with two arguments: err and
derivedKey. If an error occurs while deriving the key, err will be set;
otherwise err will be null. By default, the successfully generated
derivedKey will be passed to the callback as a Buffer. An error will be
thrown if any of the input arguments specify invalid values or types.】
iterations 参数必须是尽可能高的数字。迭代次数越多,派生的密钥就越安全,但完成所需的时间也会更长。
【The iterations argument must be a number set as high as possible. The
higher the number of iterations, the more secure the derived key will be,
but will take a longer amount of time to complete.】
salt 应尽可能唯一。建议盐值是随机的,并且至少为 16 字节长。详情请参阅 NIST SP 800-132。
【The salt should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See NIST SP 800-132 for details.】
在传递 password 或 salt 字符串时,请考虑 将字符串用作加密 API 输入时的注意事项。
【When passing strings for password or salt, please consider
caveats when using strings as inputs to cryptographic APIs.】
const {
pbkdf2,
} = await import('node:crypto');
pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});const {
pbkdf2,
} = require('node:crypto');
pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});可以使用 crypto.getHashes() 检索受支持的摘要函数数组。
【An array of supported digest functions can be retrieved using
crypto.getHashes().】
该 API 使用 libuv 的线程池,这可能对某些应用产生意想不到的负面性能影响;更多信息请参阅 UV_THREADPOOL_SIZE 文档。
【This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
UV_THREADPOOL_SIZE documentation for more information.】