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
上执行哪些验证。
const {
generateKey
} = await import('node:crypto');
generateKey('hmac', { length: 64 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
const {
generateKey,
} = require('node:crypto');
generateKey('hmac', { length: 64 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
type
: <string> The intended use of the generated secret key. Currently accepted values are'hmac'
and'aes'
.options
: <Object>length
: <number> The bit length of the key to generate. This must be a value greater than 0.- If
type
is'hmac'
, the minimum is 8, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated toMath.floor(length / 8)
. - If
type
is'aes'
, the length must be one of128
,192
, or256
.
- If
callback
: <Function>err
: <Error>key
: <KeyObject>
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: 64 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
const {
generateKey,
} = require('node:crypto');
generateKey('hmac', { length: 64 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});