Ir para o conteúdo
ToolsMinify logo
Todos os artigos

Math.random vs crypto.getRandomValues - Qual Voce Deve Usar?

Math.random serve para jogos e UI. crypto.getRandomValues e obrigatorio para senhas, tokens e sorteios justos. Entenda a diferenca, o vies de modulo e quando usar um gerador seguro no navegador.

Atualizado em 2 de novembro de 20268 min de leitura

Use o Gerador de Numeros Aleatorios - de graça

Abra a ferramenta e aplique o que você aprendeu neste guia.

Abrir Gerador de Numeros Aleatorios

JavaScript gives you two common ways to pick random numbers in the browser: Math.random and crypto.getRandomValues. They look similar in a demo, but they are not interchangeable. Math.random is a fast pseudo-random generator meant for non-security work. crypto.getRandomValues is a cryptographically secure PRNG (CSPRNG) meant for secrets, tokens, and anything an attacker should not be able to predict. This guide explains the difference, when Math.random is unsafe, how modulo bias sneaks into naive code, and how to generate secure random integers and decimals in your browser.

Quick answer

Use Math.random for animations, shuffled playlists, cosmetic UI, and games where predictability is not a security risk. Use crypto.getRandomValues for passwords, API keys, session tokens, raffle draws, unique samples, and anything that must resist prediction. ToolsMinify's Random Number Generator and Password Generator both use Web Crypto - never Math.random.

What Math.random actually does

Math.random returns a floating-point number in the half-open range [0, 1). Engines implement it with a deterministic algorithm seeded by the runtime. It is fast and good enough when you only need variety - confetti particles, a random test fixture label, or picking a tip of the day.

It is not designed to be secret. In older environments the seed or internal state could be inferred from enough outputs. Even when modern engines harden the seed, Math.random is still the wrong API for security because the platform does not promise cryptographic strength, and many tutorials wrap it with biased integer tricks.

  • Good for: UI animations, games, shuffle demos, non-sensitive sampling
  • Bad for: passwords, reset tokens, lottery-style draws, crypto nonces, API keys
  • Returns floats in [0, 1) - not integers, and not a security API

What crypto.getRandomValues does

crypto.getRandomValues is part of the Web Crypto API. You pass a typed array (for example Uint32Array) and the browser fills it with cryptographically strong random values from the operating system's entropy sources. That is the same class of randomness browsers use for TLS and other security features.

Because the values are hard to predict, they are suitable for generating secrets in the client when you do not want to send anything to a server. That is why privacy-first password and number generators prefer Web Crypto and run entirely in the browser.

  • Cryptographically secure (CSPRNG) under the Web Crypto contract
  • Works offline once the page is loaded
  • Ideal for client-side tools that must not upload secrets

Modulo bias - the silent bug in random integers

A common snippet is value = randomUint32 % n. If n does not divide the full 32-bit range evenly, some remainders appear more often than others. That bias is tiny for huge n ranges relative to 2^32, but it is real - and for small ranges used in raffles, dice, or "pick a winner" tools, you should avoid it.

Fix: rejection sampling

Draw a 32-bit value. If it falls in the incomplete leftover region at the top of the 2^32 space, discard and draw again. Only then take modulo n. Every integer in [0, n) becomes equally likely. Secure generators on ToolsMinify use this pattern.

When you need unique random numbers

Security and fairness are different jobs. A raffle that must not repeat winners needs sampling without replacement (unique draws) inside an inclusive min-max range. A password needs high entropy with replacement across a character set. Both should still start from crypto randomness - uniqueness alone does not make Math.random safe.

For inclusive integer ranges, the count of unique values cannot exceed (max - min + 1). For decimals, "unique" is usually the wrong model; generate independently or switch to whole numbers.

Generate secure random numbers in your browser

You do not need to implement rejection sampling yourself for everyday use. Open a client-side generator that already uses Web Crypto, set your range, and copy the result.

  • Random Number Generator - secure random integers or decimals, bulk lists, optional unique draws - crypto.getRandomValues in your browser.
  • Password Generator - strong random passwords with length and charset controls - same Web Crypto foundation.
  • UUID Generator - UUID v4 / v7, ULID, and NanoID for identifiers that should not collide.

Practical checklist

  1. Ask: could someone gain access, money, or unfair advantage by predicting the next value?
  2. If yes, use crypto.getRandomValues (or a tool built on it) - never Math.random.
  3. If you map random bits to a range, use rejection sampling instead of a raw modulo.
  4. For passwords and tokens, prefer a dedicated generator with a large character pool and enough length.
  5. Keep generation client-side when the secret should never hit your server logs.

Frequently asked questions

Is Math.random ever OK?

Yes - for non-security randomness. Visual variety, games without real-money stakes, and demo data are fine. The moment the number is a secret or must be fair against a motivated attacker, switch to Web Crypto.

Is crypto.getRandomValues slower?

It is slower than Math.random, but for generating passwords, a few thousand lottery numbers, or test IDs the difference is irrelevant in a browser. Correctness and unpredictability matter more than micro-benchmarks here.

Does a secure generator need a server?

No. The browser already exposes a CSPRNG. Client-side tools can generate values locally so secrets never leave the device. That is the model ToolsMinify uses.

What about Node.js crypto.randomInt?

On the server, use the platform crypto module (for example crypto.randomInt) instead of Math.random. The same rule applies: security-sensitive randomness needs a CSPRNG API.

Try a secure RNG now

Use the free Random Number Generator to draw crypto-secure integers or decimals in your browser - set min/max, optional unique mode, then copy. Nothing is uploaded.

Use o Gerador de Numeros Aleatorios - de graça

Abra a ferramenta e aplique o que você aprendeu neste guia.

Abrir Gerador de Numeros Aleatorios

Artigos relacionados