Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Math.random repeat?

For the different JavaScript implementations of Math.random:

Putting aside memory and length issues, will the following eventually have an eternally repeating sequence of numbers (e.g. It only depends on an internal seed, and when that seed wraps back to its starting point the numbers will repeat)?

sequence = Math.random();
while(true){
    sequence += ', ' + Math.random();
}

Will each client have the same repeating sequence (e.g. Clients don't incorporate client-specific data into the random number generation process)?


I ask because if the possible sequence of numbers is a limited subset, things like generating UUIDs with Math.random will have a much greater chance of collision.

like image 233
Briguy37 Avatar asked Feb 11 '23 11:02

Briguy37


2 Answers

From reading MDN:

Note: Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

I would assume, that collisions are eventually possible.

like image 110
Thomas Junk Avatar answered Feb 14 '23 01:02

Thomas Junk


This mdn doc for Math.random() says that you can not rely on this to be truly secure.

But you could still try the alternative suggested window.crypto.getRandomValues() but at the time I write this, it is still experimental.

The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Note: Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

like image 22
axelduch Avatar answered Feb 14 '23 00:02

axelduch