The documentation for this method indicates that it will throw an exception if there is insufficient entropy to generate the data. My question relates to entropy. How is it generated and can you prevent the exception from being thrown by providing adequate entropy? How common is the exception, 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.
Throws an error or calls an error callback if this is not enough accumulated entropy to generate cryptographically strong data . In other words, crypto.randomBytes will not block without a callback even if all sources of entropy are merged.
In the following example, how to properly handle the exception and completely fill the array, basically ensuring that the array is completely filled with the generated bytes. I just catch the exception and create a new array in the catch block, but will this also throw an exception? Essentially, how could I get this code to work 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) }
source share