Tag Archives: Math

Safe random numbers in JavaScript

Generating random numbers in JavaScript is really easy. Try to google them; I am pretty sure the most results will show Math.random().

Basically generating a random number in JavaScript looks like this:

Add a bit more randomness to your number by making it a natural number and adding the current time since 1970/01/01 in milliseconds.

As you can see we cast the natural number to a string before adding the current timestamp. It’s more a string concat instead of a mathematical adding. But it makes the result more unique.

In general the result of our random number is good enough to use them as a unique number in the client.

However we have a unique result – it’s not really secure. Math.random() is not desined for cryptographically use. If you want to create more secure numbers you should try window.crypto.

window.crypto is implemented by the most modern browsers. But you should always use feature detection and support a fallback if it’s not supported by the users client.

Yep, the result is always returned as a string. Remove the .toString()/” if you need a proper JavaScript number or cast the result at the end.