Search code examples
javascriptrandomcryptography

How to replace Math.random() with crypto.getRandomValues() and keep same result?


I'am using the following function to get a specific random string to pass it then to another function:

function generateRandomString() {
    return Math.random().toString(36).substring(2, 15) + 
           Math.random().toString(36).substring(2, 15);
}

I would like to use crypto.getRandomValues() instead Math.random(). How would I pass Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); as an argument to the crypto.getRandomValues(), or I'am in the wrong direction?


Solution

  • You can use it like this:

    function generateRandomString() {
         return (crypto.getRandomValues(new Uint32Array(1))[0] / 4294967295).toString(36).substring(2, 15) + (crypto.getRandomValues(new Uint32Array(1))[0] / 4294967295).toString(36).substring(2, 15);
    }
    

    Logic: Divide a random UInt32 by the maximum value (2^32 -1) to get a result between 0 and 1

    Here is the reference: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues