crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)


提供同步的基于密码的密钥派生函数 2 (PBKDF2) 实现。 应用由 digest 指定的选定 HMAC 摘要算法以从 passwordsaltiterations 导出请求字节长度 (keylen) 的密钥。

如果发生错误,将抛出 Error,否则派生密钥将作为 Buffer 返回。

如果 digestnull,则将使用 'sha1'。 此行为已弃用,请显式指定 digest

iterations 参数必须是尽可能高的数字。 迭代次数越多,派生密钥就越安全,但需要更长的时间才能完成。

salt 应该尽可能唯一。 建议盐是随机的,长度至少为 16 字节。 有关详细信息,请参阅 NIST SP 800-132

const crypto = require('crypto');
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex'));  // '3745e48...08d59ae'

crypto.DEFAULT_ENCODING 属性可用于更改返回 derivedKey 的方式。 但是,此属性已被弃用,应避免使用。

const crypto = require('crypto');
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key);  // '3745e48...aa39b34'

可以使用 crypto.getHashes() 检索支持的摘要函数数组。

Provides a synchronous 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.

If an error occurs an Error will be thrown, otherwise the derived key will be returned as a Buffer.

If digest is null, 'sha1' will be used. This behavior is deprecated, please specify a digest explicitly.

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.

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.

const crypto = require('crypto');
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex'));  // '3745e48...08d59ae'

The crypto.DEFAULT_ENCODING property may be used to change the way the derivedKey is returned. This property, however, is deprecated and use should be avoided.

const crypto = require('crypto');
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key);  // '3745e48...aa39b34'

An array of supported digest functions can be retrieved using crypto.getHashes().