Search code examples
javascriptrandomcryptographydistributionexponential-distribution

Is this exponential distribution sampler cryptographically secure?


I'm trying to create a exponential random number generator using JavaScript, which works using methods from a previous StackOverflow answer. :

function randomNumGen() {
        var u = Math.random();
        var mu = 0.3;
        return -Math.log(1.0 - u) / mu;
}

However, I later discovered that using Math.random() is not cryptographically secure from another StackOverflow answer. However, I'm not entirely sure if it is cryptographically secure in my case, as it uses the uniform randomness of u against an exponential distribution to make a sample, but I assume it isn't secure.

In the second site, it recommends other libraries, however they use different distribution, not exponential. I assume I cannot simply replace the Math.random() with their one (e.g window.crypto.getRandomValues) as it's not uniform.

Any insights on what I can do?


Solution

  • No, the presented exponential distribution sampler is cryptographically not secure. JavaScript's Math.random() is cryptographically not secure and the inverse transform method you use for sampling the distribution doesn't change this fact.

    While it's not clear to me why do you really want to use cryptographically secure source of randomness, you can, if you please.

    However you are maybe confused about the terminologies. Do you really need high amount of unpredictability for cryptographical purposes, or just high amount of statistical randomness?

    If you really need cryptographical security, then use a CSPRNG transformed to the floating-point interval [0, 1) instead of Math.random(), otherwise you should be fine with a simple high-quality PRNG.