Mehmet Egemen Albayrak
Mehmet Egemen Albayrak

Reputation: 115

Is there a better way than crypto.randomBytes to generate unique ids in performance-wise?

Node.js documentation strongly discourages the usage of crypto.randomBytes(). However as I read in an answer of StackOverflow, in all methods of random string generation such as using timestamps etc. the best way to achieve highest entropy is crypto.randomBytes().

I would like to use this uuid strategy to generate validation keys in my node.js system. Is there any other better way performance-wise?

Upvotes: 9

Views: 6458

Answers (1)

FINDarkside
FINDarkside

Reputation: 2435

If you want to use CSPRNG, not really.

Using uuid was suggested, but it simply calls crypto.randomBytes(16) and converts it to hex string. randomBytes blocking isn't really a problem, because it offers asynchronous api as well (second arg is callback). When generating such small amounts of data, using the sync api might be faster though.

Docs do still mention lack of entropy possibly causing longer block than usual. It should only be a problem right after boot though and even in that case blocking can be avoided by using the asynchronous api.

The crypto.randomBytes() method will not complete until there is sufficient entropy available. 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.

Upvotes: 4

Related Questions