crypto.randomBytes(size[, callback])


生成加密强度的伪随机数据。size 参数是一个数字,表示要生成的字节数。

【Generates cryptographically strong pseudorandom data. The size argument is a number indicating the number of bytes to generate.】

如果提供了 callback 函数,字节将异步生成,并且会使用两个参数调用 callback 函数:errbuf。如果发生错误,err 将是一个 Error 对象;否则为 nullbuf 参数是一个包含生成字节的 Buffer

【If a callback function is provided, the bytes are generated asynchronously and the callback function is invoked with two arguments: err and buf. If an error occurs, err will be an Error object; otherwise it is null. The buf argument is a Buffer containing the generated bytes.】

// Asynchronous
const {
  randomBytes,
} = await import('node:crypto');

randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});// Asynchronous
const {
  randomBytes,
} = require('node:crypto');

randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});

如果未提供 callback 函数,则会同步生成随机字节并作为 Buffer 返回。如果生成字节时出现问题,将抛出错误。

【If the callback function is not provided, the random bytes are generated synchronously and returned as a Buffer. An error will be thrown if there is a problem generating the bytes.】

// Synchronous
const {
  randomBytes,
} = await import('node:crypto');

const buf = randomBytes(256);
console.log(
  `${buf.length} bytes of random data: ${buf.toString('hex')}`);// Synchronous
const {
  randomBytes,
} = require('node:crypto');

const buf = randomBytes(256);
console.log(
  `${buf.length} bytes of random data: ${buf.toString('hex')}`);

crypto.randomBytes() 方法在有足够熵可用之前不会完成。
通常这不会超过几毫秒。唯一可能需要更长时间生成随机字节的情况是启动后不久,当整个系统的熵仍然不足时。

【The crypto.randomBytes() method will not complete until there is sufficient entropy available. This should normally never take longer than a few milliseconds. The only time when generating the random bytes may conceivably block for a longer period of time is right after boot, when the whole system is still low on entropy.】

该 API 使用 libuv 的线程池,这可能对某些应用产生意想不到的负面性能影响;更多信息请参阅 UV_THREADPOOL_SIZE 文档。

【This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.】

crypto.randomBytes() 的异步版本是在单个线程池请求中执行的。为了尽量减少线程池任务时长的差异,在作为完成客户端请求的一部分时,应将大型的 randomBytes 请求进行分割。

【The asynchronous version of crypto.randomBytes() is carried out in a single threadpool request. To minimize threadpool task length variation, partition large randomBytes requests when doing so as part of fulfilling a client request.】