crypto.generateKeySync(type, options)


  • type <string> 生成的秘密密钥的预期用途。目前可接受的值为 'hmac''aes'
  • options <Object>
    • length <number> 要生成的密钥的位长度。
      • 如果 type'hmac',最小值为 8,最大长度为 231-1。如果值不是 8 的倍数,生成的密钥将被截断为 Math.floor(length / 8)
      • 如果 type'aes',长度必须为 128192256
  • 返回: <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..........41econst {
  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.】