Dev.to Security 🔐 Cybersecurity 👁 0 📖 5 min read

Why Math.random() Is Unsafe for Password Generation (And What to Use Instead)

JavaScript makes it remarkably easy to generate random-looking strings. But when those strings are intended to protect accounts, API credentials, or sensitive systems, the source of randomness matters. A password can lo

JavaScript makes it remarkably easy to generate random-looking strings. But when those strings are intended to protect accounts, API credentials, or sensitive systems, the source of randomness matters.

A password can look complicated and still be vulnerable if the underlying random number generator is predictable.

Let's examine why Math.random() is unsuitable for password generation and build a more secure alternative using the browser's native Web Crypto API.

The problem with Math.random()

A common password generator implementation looks something like this:

const characters =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

function generatePassword(length = 16) {
  let password = "";

  for (let i = 0; i < length; i++) {
    const index = Math.floor(
      Math.random() * characters.length
    );

    password += characters[index];
  }

  return password;
}

This produces random-looking strings, but there is a critical security problem.

Math.random() is not a cryptographically secure random number generator (CSPRNG).

JavaScript engines are not required to implement it using cryptographically secure algorithms. It is designed for general-purpose randomization, not for generating authentication secrets.

For passwords, session tokens, and other security-sensitive values, we need a different approach.

The solution: crypto.getRandomValues()

Modern browsers expose the Web Crypto API, including:

crypto.getRandomValues()

This method fills a typed array with cryptographically strong random values.

For example:

const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);

The result is 16 random bytes supplied by the browser's cryptographic random number generator.

We can use these bytes to select characters from a password alphabet.

However, one additional detail matters: avoiding modulo bias.

Why modulo bias matters

Suppose our password alphabet contains 70 characters.

A random byte has 256 possible values, ranging from 0 to 255.

We might map those values into our character set with:

const index = randomByte % 70;

But 256 is not evenly divisible by 70.

This means certain character indexes occur more frequently than others.

The result is a nonuniform distribution, which reduces the theoretical entropy compared with perfectly uniform character selection.

The fix is called rejection sampling.

We discard byte values that would introduce bias, then generate additional bytes until we have enough valid selections.

Building a secure JavaScript password generator

Here's a complete example that uses the Web Crypto API and rejection sampling.

const CHARSET =
  "ABCDEFGHJKLMNPQRSTUVWXYZ" +
  "abcdefghijkmnopqrstuvwxyz" +
  "23456789" +
  "!@#$%^&*";

function generateSecurePassword(length = 20) {
  if (
    !Number.isInteger(length) ||
    length < 1 ||
    length > 128
  ) {
    throw new RangeError(
      "Length must be an integer from 1 to 128"
    );
  }

  const alphabetSize = CHARSET.length;

  // Largest multiple of alphabetSize within
  // the 0-255 byte range.
  const maxValid =
    256 - (256 % alphabetSize);

  const bytes = new Uint8Array(32);

  let password = "";

  while (password.length < length) {
    crypto.getRandomValues(bytes);

    for (const byte of bytes) {
      // Reject values that introduce modulo bias.
      if (byte >= maxValid) {
        continue;
      }

      const index = byte % alphabetSize;
      password += CHARSET[index];

      if (password.length === length) {
        break;
      }
    }
  }

  return password;
}

// Run in your browser's developer console.
generateSecurePassword(20);

What this implementation gets right

  1. Cryptographic randomness: It uses crypto.getRandomValues() rather than Math.random().
  2. Unbiased character selection: Rejection sampling ensures each character in the alphabet has equal selection probability.
  3. Independent selection: Each accepted random byte determines one character independently.
  4. Input validation: The function restricts password length to a reasonable range.
  5. No external dependencies: The example uses native browser functionality.

The sample alphabet also excludes several visually ambiguous characters, making generated passwords easier to transcribe.

This is a minimal educational implementation. A production generator may offer additional options, handle more character sets, and provide a secure interface for copying generated credentials.

What about NIST password recommendations?

NIST released Revision 4 of its Digital Identity Guidelines in July 2025.

Its password guidance emphasizes length, support for password managers, and avoiding unnecessary composition requirements.

For centrally verified passwords, NIST SP 800-63B-4 specifies:

  • A minimum of 15 characters when passwords are used as the sole authentication factor.
  • A minimum of eight characters when passwords are used as part of multi-factor authentication.
  • Support for maximum password lengths of at least 64 characters is recommended.
  • Verifiers must not impose mandatory character composition rules.
  • Verifiers must not require periodic password changes without evidence of compromise.

These are requirements for authentication systems and password verifiers, not a mandate that every password generator use a particular default length.

For randomly generated passwords, a 20-character default is a practical choice when the destination service supports it.

See the official NIST SP 800-63B guidance.

Password entropy: why length and randomness matter

For passwords generated by independently choosing characters uniformly from an alphabet, theoretical entropy can be calculated as:

Entropy = password length × log₂(alphabet size)

For example, a 20-character password drawn uniformly from 64 possible characters has:

20 × log₂(64) = 120 bits of entropy

That's a substantial search space, assuming the generator actually provides unbiased, independent random selections.

This distinction is important: adding symbols to a password doesn't automatically make it secure if the underlying selection process is predictable.

Security considerations beyond randomness

Even an excellent random number generator cannot compensate for an insecure application.

When building a browser-based password generator:

  • Avoid transmitting generated passwords to analytics services, APIs, or logging systems.
  • Never log production passwords to the developer console.
  • Do not persist generated credentials without an explicit and appropriate security design.
  • Minimize third-party scripts on pages handling sensitive credentials.
  • Consider clipboard exposure and the risks associated with compromised browser extensions.
  • Encourage users to save unique passwords in a reputable password manager.

Generating credentials locally is useful for privacy, but it does not eliminate every browser or endpoint security risk.

Putting these principles into practice

I've been working on Generate My Password, a free browser-based password generation utility that applies these principles to everyday credential creation.

It provides configurable password lengths, character selection, and additional password-related utilities.

The project focuses on generating credentials directly in the browser rather than requiring a server to generate or store them.

The JavaScript example in this article is a standalone demonstration of the underlying techniques, not a reproduction of the website's source code.

Secure Randomness Matters

Password generation is one of those tasks where a seemingly small implementation detail can have major security implications.

The difference between Math.random() and a cryptographically secure random number generator may not be apparent from the resulting string.

But under the hood, that distinction matters.

If you're building a password generator in JavaScript, start with crypto.getRandomValues(), use unbiased character selection, and keep sensitive credentials out of unnecessary storage and network requests.

Secure password generation begins with secure randomness.

References

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.