In what situations is it acceptable (from a security standpoint) to use node's crypto.pseudoRandomBytes
instead of the cryptographically-strong crypto.randomBytes
?
I assume (incorrect), but the docs don't really have much to say about how less-strong it is.pseudoRandomBytes
performs better at the expense of being more predictable
Specifically, I'm wondering if I'm ok using pseudoRandomBytes
to generate a CSRF token.
randomBytes() method is used to generate a cryptographically well-built artificial random data and the number of bytes to be generated in the written code. Syntax: crypto.randomBytes( size, callback )
It includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. crypto is built into Node. js, so it doesn't require rigorous implementation process and configurations. Unlike other modules, you don't need to install Crypto before you use it in your Node.
randomBytes() generates cyprtographically strong pseudo-random data. This method will not be completed until there is sufficient entropy in the bytes created. But even after this it does not takes more than a few milliseconds. This method basically creates a few random bytes which are further used.
GenerateRandomBytesToHex function returns you a hash that is X Byte long inside of a String where each Byte is displayed in hexadecimal value. The hexidecimal value of the number 42 is 0x2A . You can see that one Byte (from 0 to 254) is displayed using 2 character in hexadecimal.
As it turns out, with the default OpenSSL (which is bundled with node, but if you've built your own, it is possible to configure different engines), the algorithm to generate random data is exactly the same for both randomBytes
(RAND_bytes
) and pseudoRandomBytes
(RAND_pseudo_bytes
).
The one and only difference between the two calls depends on the version of node you're using:
randomBytes
returns an error if the entropy pool has not yet been seeded with enough data. pseudoRandomBytes
will always return bytes, even if the entropy pool has not been properly seeded.randomBytes
does not return until the entropy pool has enough data. This should take only a few milliseconds (unless the system has just booted).Once the the entropy pool has been seeded with enough data, it will never "run out," so there is absolutely no effective difference between randomBytes
and pseudoRandomBytes
once the entropy pool is full.
Because the exact same algorithm is used to generate randrom data, there is no difference in performance between the two calls (one-time entropy pool seeding notwithstanding).
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