crypto.generateKey(type, options, callback)
type:<string> 生成的密钥的预期用途。目前接受的值有'hmac'和'aes'。options:<Object>length:<number> 要生成的密钥的位长度。该值必须大于 0。- 如果
type为'hmac',最小值为 8,最大长度为 231-1。如果该值不是 8 的倍数,生成的密钥将被截断为Math.floor(length / 8)。 - 如果
type为'aes',长度必须为128、192或256之一。
- 如果
callback:<Function>err:<Error>key:<KeyObject>
异步生成一个指定 length 的新随机密钥。type 将决定对 length 执行哪些验证。
【Asynchronously generates a new random secret key of the given length. The
type will determine which validations will be performed on the length.】
const {
generateKey,
} = await import('node:crypto');
generateKey('hmac', { length: 512 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});const {
generateKey,
} = require('node:crypto');
generateKey('hmac', { length: 512 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});生成的 HMAC 密钥的大小不应超过底层哈希函数的块大小。更多信息请参见 crypto.createHmac()。
【The size of a generated HMAC key should not exceed the block size of the
underlying hash function. See crypto.createHmac() for more information.】