crypto.generateKeySync(type, options)
-
type
:<string> 生成的密钥的预期用途。当前接受的值为'hmac'
和'aes'
。¥
type
: <string> The intended use of the generated secret key. Currently accepted values are'hmac'
and'aes'
. -
options
:<Object>-
length
:<number> 要生成的密钥的位长度。¥
length
: <number> The bit length of the key to generate.-
如果
type
是'hmac'
,则最小长度为 8,最大长度为 231-1。如果该值不是 8 的倍数,则生成的密钥将被截断为Math.floor(length / 8)
。¥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)
. -
如果
type
是'aes'
,则长度必须是128
、192
或256
之一。¥If
type
is'aes'
, the length must be one of128
,192
, or256
.
-
-
-
返回:<KeyObject>
¥Returns: <KeyObject>
同步生成给定 length
的新的随机的密钥。type
将确定将在 length
上执行哪些验证。
¥Synchronously generates a new random secret key of the given length
. The
type
will determine which validations will be performed on the length
.
const {
generateKeySync,
} = await import('node:crypto');
const key = generateKeySync('hmac', { length: 512 });
console.log(key.export().toString('hex')); // e89..........41e
const {
generateKeySync,
} = require('node:crypto');
const key = generateKeySync('hmac', { length: 512 });
console.log(key.export().toString('hex')); // e89..........41e
生成的 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.