crypto.randomBytes(size[, callback])


生成加密强伪随机数据。 size 参数是指示要生成的字节数的数值。

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

// 异步的。
const crypto = require('crypto');
crypto.randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} 位的随机数据: ${buf.toString('hex')}`);
});

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

// 同步的。
const buf = crypto.randomBytes(256);
console.log(
  `${buf.length} 位的随机数据: ${buf.toString('hex')}`);

crypto.randomBytes() 方法将在获得足够的熵之后完成。 这通常不会超过几毫秒。 只有在刚开启时才可能会阻塞更久,因为此时整个系统的熵不多。

这个 API 使用 libuv 的线程池,所以在某些时候可能会产生意外的性能问题,查看 UV_THREADPOOL_SIZE 的文档以了解更多信息。

crypto.randomBytes() 的异步版本在单个线程池请求中执行。 要最小化线程池任务长度变化,请在执行此操作时对大型的 randomBytes 请求进行分区,以完成客户端请求。

Generates cryptographically strong pseudo-random data. The size argument is a number indicating the number of bytes to generate.

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 crypto = require('crypto');
crypto.randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});

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 buf = crypto.randomBytes(256);
console.log(
  `${buf.length} bytes of random data: ${buf.toString('hex')}`);

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.

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.

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.