crypto.randomBytes(size[, callback])
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 block until there is sufficient entropy. 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.
Please login to continue.