Create Truly Strong Passwords in PHP: A Secure Generator with Cryptographic Randomness and Zero Bias

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Deep down, we all know that “123456”, “password”, your dog’s name, or your birth year aren’t exactly secure passwords… and yet we keep using them.

The most alarming statistic: according to various studies in recent years, between 76% and 81% of security breaches involve weak or reused credentials.

That’s why today we are going to build a truly robust password generator in PHP step by step, using cryptographic randomness and avoiding the common biases found in many homegrown implementations.

What is the difference between “random” and “cryptographically secure”?

When we use rand(), mt_rand(), or even the classic rand(1000000, 9999999) to generate codes or passwords, we are working with pseudo-random number generators (PRNGs).

They are very useful for games, animations, simulations… but not for security.

The primary reason is that if an attacker discovers:

  • the algorithm
  • the initial seed
  • or just a few consecutive outputs

…in many cases, they can reconstruct the entire future sequence.

For passwords (and any cryptographic secret), we need something much stronger: cryptographically secure randomness (CSPRNG).

In modern PHP (≥7.0), the recommended and simplest approach is to use random_bytes().

This function leverages entropy sources from the operating system (hardware interrupts, kernel events, etc.), making the output unpredictable even to someone who knows all prior internal states.

The Code – generateSecurePassword() Function

<?php

/**
 * Genera una contraseña fuerte usando aleatoriedad criptográfica sin sesgos
 * 
 * @param int    $length        Longitud deseada (mínimo 8)
 * @param bool   $useNumbers    Incluir números
 * @param bool   $useLowercase  Incluir minúsculas
 * @param bool   $useUppercase  Incluir mayúsculas
 * @param bool   $useSymbols    Incluir símbolos
 * @param bool   $useSpaces     Incluir espacios (¡cuidado con esta opción!)
 * @param string $customSymbols Símbolos personalizados (si se envía, reemplaza los predeterminados)
 * 
 * @return string Contraseña generada
 */
function generateSecurePassword(
    int $length = 12,
    bool $useNumbers = true,
    bool $useLowercase = true,
    bool $useUppercase = true,
    bool $useSymbols = true,
    bool $useSpaces = false,
    string $customSymbols = ''
): string {
    // Protección básica contra longitudes peligrosamente cortas
    $length = max(8, $length);

    // Conjuntos de caracteres
    $numbers   = '0123456789';
    $lowercase = 'abcdefghijklmnopqrstuvwxyz';
    $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $symbols   = $customSymbols !== '' 
        ? $customSymbols 
        : '!@#$%^&*()-_=+[]{}|;:,.<>?/~`';

    $spaces = ' ';

    // Construimos el pool completo según las opciones elegidas
    $chars = '';
    if ($useNumbers)    $chars .= $numbers;
    if ($useLowercase)  $chars .= $lowercase;
    if ($useUppercase)  $chars .= $uppercase;
    if ($useSymbols)    $chars .= $symbols;
    if ($useSpaces)     $chars .= $spaces;

    // Caso extremo: el usuario desactivó TODO → fallback razonable
    if ($chars === '') {
        $chars = $lowercase . $uppercase . $numbers;
    }

    $charsLength = strlen($chars);

    // Generador de índice aleatorio sin sesgo (rejection sampling)
    $getUnbiasedIndex = function (int $max) use (&$random_bytes): int {
        $maxSafe = (floor(255 / $max)) * $max;

        do {
            $byte = random_bytes(1);
            $value = ord($byte);
        } while ($value >= $maxSafe);

        return $value % $max;
    };

    // Generamos la contraseña base
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $index = $getUnbiasedIndex($charsLength);
        $password .= $chars[$index];
    }

    // Garantizamos al menos un carácter de cada tipo solicitado
    $required = [];
    if ($useNumbers)    $required[] = $numbers[random_int(0, 9)];
    if ($useLowercase)  $required[] = $lowercase[random_int(0, 25)];
    if ($useUppercase)  $required[] = $uppercase[random_int(0, 25)];
    if ($useSymbols)    $required[] = $symbols[random_int(0, strlen($symbols) - 1)];
    if ($useSpaces)     $required[] = ' ';

    // Mezclamos las posiciones donde insertaremos los caracteres obligatorios
    $positions = range(0, $length - 1);
    shuffle($positions); // ← ¡shuffle usa Mersenne Twister, pero solo para posiciones!

    foreach ($required as $i => $char) {
        if (isset($positions[$i])) {
            $password[$positions[$i]] = $char;
        }
    }

    return $password;
}

Key Points That Make This Generator Different (and More Secure)

  • Uses random_bytes() → cryptographically secure source
  • Rejection sampling to prevent modulo bias (crucial when the pool length is not a power of 2)
  • Guarantees at least one character of each type without sacrificing overall randomness
  • Offers great flexibility (length, character sets, custom symbols)
  • Sensible fallback if the user disables all options

Quick Usage Example

$pass = generateSecurePassword(
    length: 16,
    useNumbers: true,
    useLowercase: true,
    useUppercase: true,
    useSymbols: true,
    customSymbols: '!@#*_$%'
);

echo "Contraseña generada:  " . $pass;
// Ejemplo de salida:  kP$9mW#vL2qR*8nT

Quick Final Recommendations

  • Lengths ≥14–16 characters are the recommended standard in 2025–2026 for most applications
  • Never store passwords in plain text → always use password_hash()
  • Consider offering a passphrase option (e.g., 4–6 words) in user interfaces
  • If you need to generate many passwords in batch → consider calling random_bytes() in bulk (more efficient)

Password security is not just about length, but about the quality of the randomness. With random_bytes() and zero bias, this generator is unbeatable for everyday applications. You can extend it with passphrases or by excluding ambiguous characters (such as ‘O’ vs. ‘0’) in future iterations.

Implement this function today and elevate your app’s security. Your users will thank you! Are you ready to try it out? Explore the depths of improving key generation in your application! Let’s keep coding.