Does Crypto.randomBytes processing exception relate to inadequate entropy?

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) } 
+6
source share
1 answer

If entropy is not available, it is best to wait a bit and try again. How long you will have to wait depends on how much entropy you need and how the sources of entropy work.

In practice, I doubt that you will have a problem. I do not know what Node.js does under covers, equivalent functions in other libraries are usually implemented as calls to the OS entropy pool. /dev/urandom or CryptGenRandom() - or as CSPRNG, which are sown from the OS entropy pool. In any case, you will never block.

Locking is only a problem if you are reading from /dev/random on Linux. This is because /dev/random may block on Linux, but not on other platforms. It can also be a problem if you read directly from hardware RNG.

+2
source

Source: https://habr.com/ru/post/971788/


All Articles