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 上执行哪些验证。

const {
  generateKeySync
} = await import('node:crypto');

const key = generateKeySync('hmac', { length: 64 });
console.log(key.export().toString('hex'));  // e89..........41econst {
  generateKeySync,
} = require('node:crypto');

const key = generateKeySync('hmac', { length: 64 });
console.log(key.export().toString('hex'));  // e89..........41e
  • 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.
      • 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 to Math.floor(length / 8).
      • If type is 'aes', the length must be one of 128, 192, or 256.
  • Returns: <KeyObject>

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: 64 });
console.log(key.export().toString('hex'));  // e89..........41econst {
  generateKeySync,
} = require('node:crypto');

const key = generateKeySync('hmac', { length: 64 });
console.log(key.export().toString('hex'));  // e89..........41e