crypto.generateKeySync(type, options)
type: <string> 生成的密钥的预期用途。 当前接受的值为'hmac'和'aes'。options: <Object>length: <number> 要生成的密钥的位长。- 如果
type为'hmac',则最小为 8,最大长度为 231-1。 如果该值不是 8 的倍数,则生成的密钥将被截断为Math.floor(length / 8)。 - 如果
type是'aes',则长度必须是128、192或256之一。
- 如果
- 返回: <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..........41etype: <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
typeis'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
typeis'aes', the length must be one of128,192, or256.
- If
- 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