crypto.generateKey(type, options, callback)
-
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> 要生成的密钥的位长度。这必须是一个大于 0 的值。¥
length<number> The bit length of the key to generate. This must be a value greater than 0.-
如果
type是'hmac',则最小长度为 8,最大长度为 231-1。如果该值不是 8 的倍数,则生成的密钥将被截断为Math.floor(length / 8)。¥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). -
如果
type是'aes',则长度必须是128、192或256之一。¥If
typeis'aes', the length must be one of128,192, or256.
-
-
-
callback<Function>-
err<Error> -
key<KeyObject>
-
异步生成给定 length 的新的随机的密钥。type 将确定将在 length 上执行哪些验证。
¥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: 512 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});const {
generateKey,
} = require('node:crypto');
generateKey('hmac', { length: 512 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});生成的 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.