javascriptnode.jsrandomcryptojs

Generate random value 0 to 1 using `crypto-js` library


I'm working on a small JS library, it consists of several npm packages for Web, NodeJS and React Native, but all of them use the shared core library.

In the core library I've been using Math.random(), but recently found some nasty randomness issues resulting in a lot of duplicates for certain versions of some React Native engines. I decided to switch to a single source of truth for rng that will be consistent between platforms.

I already use crypto-js for sha256 and it would be amazing if I could utilize crypto-js for switching from Math.random() too.

I checked crypto-js docs and only found CryptoJS.lib.WordArray.random to generate random bytes, other things seem to be hashing and cipher related. I'm pretty sure it's possible to transform those bytes to 0-1 random value, but I'm not entirely sure if it could be more reliable than Math.random().

Question: Is there a way to generate reliable random 0 - 1 value similar to Math.random() using crypto-js?


Solution

  • I ended up using a dedicated library for React Native due to no Math.random() alternatives available natively

    The library is react-native-get-random-values and it uses IOS/Android native implementations for crypto