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?
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
crypto.getRandomValues()
. Is this possible?
– k.vincent
Commented
Oct 8, 2019 at 12:09
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.