简体   繁体   中英

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?

You could use the npm package uuid .

Example:

const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '0b3e4d7a-1c48-4fb7-ba10-e054f99aacfb'

As generating random string is always expensive task on CPU but guid is way better that crypto.randomBytes() .

Or you can use following thing to generate it

 Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);

But this is not recommended.

Please follow this awesome gist by joepie91 for more details.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM