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

admin2025-04-19  0

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?

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?

Share asked Oct 8, 2019 at 11:59 k.vincentk.vincent 4,1738 gold badges43 silver badges85 bronze badges 2
  • As far as I'm aware, the argument for crypto.getRandomValues() is a typed array, so, what exactly do you mean as use Math.random() .... as "an argument" ? – Nick Parsons Commented Oct 8, 2019 at 12:09
  • Yes, You're right. Just did find out here: developer.mozilla/en-US/docs/Web/API/Crypto/getRandomValues. And yes, I would like to a random string using the crypto.getRandomValues(). Is this possible? – k.vincent Commented Oct 8, 2019 at 12:09
Add a ment  | 

2 Answers 2

Reset to default 6

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/en-US/docs/Web/API/Crypto/getRandomValues

I want to ment on the answer above. Math.random() generates a number from 0 to <1 as mentioned here:

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

But the answer used the number 4294967295, so in that case, we may have 1 in the result. We have to use 4294967296 to get the value which always will be from 0 to <1.

So the correct secure version for Math.random() is:

crypto.getRandomValues(new Uint32Array(1))[0] / 4294967296

You may also find on the internet different examples of representation of 4294967296, for example 0xFFFFFFFF + 1 or 2 ** 32.

I am not a security expert, but that is what I noticed researching the internet.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745053871a282281.html

最新回复(0)