In the documentation for this method it states that it will throw an exception if there is an inadequate amount of entropy to generate the data. My question pertains to the entropy. How is it generated and can you prevent an exception from being thrown by providing adequate entropy? How common will an exception be thrown, or is it unknown?
Documentation for crypto.randomBytes
:
crypto.randomBytes(size, [callback])
// async
crypto.randomBytes(256, function(ex, buf) {
if (ex) throw ex;
console.log('Have %d bytes of random data: %s', buf.length, buf);
});
Generates cryptographically strong pseudo-random data.
Will throw error or invoke callback with error, if there is not enough accumulated entropy to generate cryptographically strong data. In other words, crypto.randomBytes without callback will not block even if all entropy sources are drained.
In the following example, how would I handle an exception properly and still completely fill the array, basically ensuring the array has been filled completely with the generated bytes. Would I just catch the exception and generate a new array within the catch block, but would if that also throws an exception? Essentially how would I make this code work properly 100% of the time?
var codes = [];
for(var i = 0;i < 100;i++){
(function(i){
crypto.randomBytes(256, function(ex, buf) {
if (ex) throw ex;
codes[i] = buf.toString('hex');
});
})(i)
}
If no entropy is available, your best bet would be to wait a bit and try again. How long you'd need to wait depends on how much entropy you need and how the underlying entropy sources work.
In practice, I doubt that you'll have any problems. I don't know what Node.js does under the covers, equivalent functions in other libraries are generally implemented as calls to the OS's entropy pool - e.g. /dev/urandom
or CryptGenRandom()
- or as CSPRNGs that are seeded from the OS's entropy pool. In either case, you'll never block.
Blocking is only an issue if you're reading from /dev/random
on Linux. This is because /dev/random
may block on Linux, but doesn't on other platforms. It could also be an issue if you're reading directly from a hardware RNG.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With