▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/passwords/code-examples$ _

Password Generator Code Examples

Secure random passwords with and without symbols in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

Each example below implements the same function: a password of a given length drawn from lowercase, uppercase and digits, with 26 symbols added on request, then prints a 16-character password with symbols and a 12-character one without. The guide covers how strong those passwords are, what current guidance says about length and composition rules, and what to do with a password after generating it. Prefer no code? The interactive Passwords generator does the same in the browser.

How strong is a generated password?

When every character is picked independently and uniformly, strength is simple arithmetic: length × log2(pool size). The pool in these examples is 62 characters without symbols and 88 with the 26 symbols !@#$%^&*()-_=+[]{}|;:,.<>?.

  • 12 characters from 62: about 71 bits.
  • 16 characters from 62: about 95 bits.
  • 16 characters from 88: about 103 bits.
  • 20 characters from 62: about 119 bits.

Length pays more than symbols: adding the 26 symbols raises each character from 5.95 to 6.46 bits, while one extra character adds a full 5.95. For an online login protected by rate limiting, 70 bits is far beyond reach; for a password that guards an encryption key or a password-manager vault, where an attacker can test offline, aim for 100 bits or more.

Length, character classes and current guidance

NIST SP 800-63B (revision 4, 2025) asks verifiers to accept passwords of at least 64 characters, to require at least 15 characters for passwords used as the only factor (8 alongside a second factor), and to drop composition rules such as “one digit and one symbol”. Many sites still enforce those rules, and a uniform random pick from all classes can miss one: a 12-character password from the 62-character pool contains no digit about 12% of the time. If a target system rejects such passwords, draw again until the password passes rather than forcing a digit into a fixed position, which makes the pattern predictable. Regenerating costs almost nothing in entropy.

The generator must be cryptographic

A password is a secret, so there is no case on this page where the fast default generator is acceptable. Every example uses the operating system's cryptographic source: random_int(), crypto.getRandomValues(), secrets.choice(), SecureRandom, RandomNumberGenerator, crypto/rand or Ruby's SecureRandom. A password built from Math.random() or mt19937 may look identical, but its real strength is capped by the generator's internal state or seed, often 32 bits, which a laptop exhausts in minutes no matter how long the password is.

Common mistakes

  • Storing or logging the generated password. Hash it immediately with Argon2id, scrypt or bcrypt (PHP's password_hash(), for example), show it once, and keep it out of logs, analytics and error reports.
  • Symbols that break the destination. $ and backticks are expanded by shells, & and ? break unencoded URLs, quotes break hand-built config files, and some legacy systems reject < and >. Remove the symbols the target cannot handle and add length instead.
  • Look-alike characters in passwords people type. A temporary password read from a screen or a letter is easier to enter without l, 1, I, O and 0; dropping five characters from 88 costs less than 0.1 bit per character.
  • Emailing a permanent password. Send a single-use reset link, or force a change at first login.

Common Use Cases

  • Initial or temporary passwords for new user accounts and resets
  • Passwords for service accounts, databases and other machine credentials
  • Password generator features in apps, browser extensions and CLI tools
  • Bulk account provisioning and seeding test users
  • Test data for password policies and strength meters

Password Generator Code Examples in PHP

Generate secure random passwords in PHP using random_bytes() for cryptographically secure random data. This approach creates strong passwords with customizable length and character sets.

<?php
// Generate a random password with default settings
function generatePassword($length = 16, $includeSpecial = true) {
    $lowercase = 'abcdefghijklmnopqrstuvwxyz';
    $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $numbers = '0123456789';
    $special = '!@#$%^&*()-_=+[]{}|;:,.<>?';

    $chars = $lowercase . $uppercase . $numbers;
    if ($includeSpecial) {
        $chars .= $special;
    }

    $password = '';
    $charsLength = strlen($chars);

    for ($i = 0; $i < $length; $i++) {
        $randomIndex = random_int(0, $charsLength - 1);
        $password .= $chars[$randomIndex];
    }

    return $password;
}

// Generate a 16-character password with special characters
$password = generatePassword(16, true);
echo $password;  // Example: aB3$xY7!mN2@pQ9&

// Generate a 12-character password without special characters
$simplePassword = generatePassword(12, false);
echo $simplePassword;  // Example: aB3xY7mN2pQ9

How it works in PHP

This function uses random_int() to generate cryptographically secure random indices for character selection. It allows customization of password length and character sets. For maximum security, always include uppercase, lowercase, numbers, and special characters.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

PHP notes

  • random_int() raises an exception rather than return weak values if no secure source is available.
  • PHP 8.3+ (new Random\Randomizer())->getBytesFromString($chars, $length) replaces the loop with one call.
  • Hash with password_hash($password, PASSWORD_ARGON2ID) where available; PASSWORD_DEFAULT is bcrypt, which ignores input beyond 72 bytes.

Password Generator Code Examples in JavaScript

Generate secure random passwords in JavaScript using crypto.getRandomValues() for cryptographically secure random values. Works in both browsers and Node.js.

function generatePassword(length = 16, includeSpecial = true) {
    const lowercase = 'abcdefghijklmnopqrstuvwxyz';
    const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const numbers = '0123456789';
    const special = '!@#$%^&*()-_=+[]{}|;:,.<>?';

    let chars = lowercase + uppercase + numbers;
    if (includeSpecial) {
        chars += special;
    }

    const array = new Uint32Array(length);
    crypto.getRandomValues(array);

    let password = '';
    for (let i = 0; i < length; i++) {
        password += chars[array[i] % chars.length];
    }

    return password;
}

// Generate a 16-character password with special characters
const password = generatePassword(16, true);
console.log(password);  // Example: aB3$xY7!mN2@pQ9&

// Generate a 12-character password without special characters
const simplePassword = generatePassword(12, false);
console.log(simplePassword);  // Example: aB3xY7mN2pQ9

How it works in JavaScript

The function fills a Uint32Array with crypto.getRandomValues(), one cryptographically secure 32-bit value per character, and maps each value onto the pool with the modulo operator. With 32-bit values and an 88-character pool the bias is below one part in 48 million, too small to affect strength. It runs in all current browsers and in Node.js 19+, where crypto is a global.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

JavaScript notes

  • In Node.js before 19, use require('node:crypto').webcrypto.getRandomValues or crypto.randomInt(chars.length) per character.
  • Generating passwords in the browser keeps them off your server, but a page with third-party scripts can read them from the DOM.
  • Copying to the clipboard with navigator.clipboard.writeText() requires a secure context and a focused page; Firefox and Safari also require a user gesture.

Password Generator Code Examples in Python

Generate secure random passwords in Python using the secrets module for cryptographically secure random generation. Perfect for security-sensitive applications.

import secrets
import string

def generate_password(length=16, include_special=True):
    lowercase = string.ascii_lowercase
    uppercase = string.ascii_uppercase
    numbers = string.digits
    special = '!@#$%^&*()-_=+[]{}|;:,.<>?'

    chars = lowercase + uppercase + numbers
    if include_special:
        chars += special

    password = ''.join(secrets.choice(chars) for _ in range(length))
    return password

# Generate a 16-character password with special characters
password = generate_password(16, True)
print(password)  # Example: aB3$xY7!mN2@pQ9&

# Generate a 12-character password without special characters
simple_password = generate_password(12, False)
print(simple_password)  # Example: aB3xY7mN2pQ9

How it works in Python

The secrets module is specifically designed for generating cryptographically strong random data suitable for security purposes. secrets.choice() securely selects random characters from the character set.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

Python notes

  • secrets.choice() uses random.SystemRandom, which reads os.urandom().
  • The Python docs' recipe for a password with at least one lowercase, one uppercase and three digits loops until any() checks pass, the same retry approach as in the guide.
  • random.choice() has the same signature as secrets.choice(), so check imports in code review.

Password Generator Code Examples in Java

Generate secure random passwords in Java using SecureRandom for cryptographically secure random generation. Suitable for enterprise applications and security-critical systems.

import java.security.SecureRandom;

public class PasswordGenerator {
    private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String NUMBERS = "0123456789";
    private static final String SPECIAL = "!@#$%^&*()-_=+[]{}|;:,.<>?";

    public static String generatePassword(int length, boolean includeSpecial) {
        SecureRandom random = new SecureRandom();
        String chars = LOWERCASE + UPPERCASE + NUMBERS;
        if (includeSpecial) {
            chars += SPECIAL;
        }

        StringBuilder password = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            password.append(chars.charAt(index));
        }

        return password.toString();
    }

    public static void main(String[] args) {
        // Generate a 16-character password with special characters
        String password = generatePassword(16, true);
        System.out.println(password);  // Example: aB3$xY7!mN2@pQ9&

        // Generate a 12-character password without special characters
        String simplePassword = generatePassword(12, false);
        System.out.println(simplePassword);  // Example: aB3xY7mN2pQ9
    }
}

How it works in Java

SecureRandom provides cryptographically strong random number generation using platform-specific sources of randomness. This implementation uses StringBuilder for efficient string construction.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

Java notes

  • Reuse one SecureRandom (it is thread-safe) instead of creating one per password.
  • Return a char[] instead of a String when the password must be wiped after use; strings are immutable and stay in memory until collected.
  • SecureRandom.getInstanceStrong() can block on Linux; the default constructor is the right choice for servers.

Password Generator Code Examples in C#

Generate secure random passwords in C# using RandomNumberGenerator for cryptographically secure random data. Perfect for ASP.NET and .NET applications.

using System;
using System.Security.Cryptography;
using System.Text;

class PasswordGenerator
{
    private const string Lowercase = "abcdefghijklmnopqrstuvwxyz";
    private const string Uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private const string Numbers = "0123456789";
    private const string Special = "!@#$%^&*()-_=+[]{}|;:,.<>?";

    public static string GeneratePassword(int length = 16, bool includeSpecial = true)
    {
        string chars = Lowercase + Uppercase + Numbers;
        if (includeSpecial)
        {
            chars += Special;
        }

        using (var rng = RandomNumberGenerator.Create())
        {
            var password = new StringBuilder(length);
            byte[] randomBytes = new byte[length * 4];
            rng.GetBytes(randomBytes);

            for (int i = 0; i < length; i++)
            {
                uint randomValue = BitConverter.ToUInt32(randomBytes, i * 4);
                password.Append(chars[(int)(randomValue % chars.Length)]);
            }

            return password.ToString();
        }
    }

    static void Main()
    {
        // Generate a 16-character password with special characters
        string password = GeneratePassword(16, true);
        Console.WriteLine(password);  // Example: aB3$xY7!mN2@pQ9&

        // Generate a 12-character password without special characters
        string simplePassword = GeneratePassword(12, false);
        Console.WriteLine(simplePassword);  // Example: aB3xY7mN2pQ9
    }
}

How it works in C#

RandomNumberGenerator fills a buffer with cryptographically secure bytes, four per character. Each 4-byte group is read as an unsigned 32-bit value and reduced modulo the pool size, which leaves a bias below one part in 48 million for 88 characters. StringBuilder assembles the password.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

C# notes

  • .NET 8+ replaces the loop with RandomNumberGenerator.GetString(chars, length), which is also free of modulo bias.
  • ASP.NET Core Identity checks policies with PasswordOptions (RequiredLength, RequireNonAlphanumeric…); generate passwords that satisfy the configured options.
  • The static RandomNumberGenerator methods are thread-safe; System.Random must never generate passwords.

Password Generator Code Examples in C++

Generate secure random passwords in C++ using the modern <random> library with random_device for secure seeding. Works with C++11 and later.

#include <iostream>
#include <string>
#include <random>

std::string generatePassword(int length = 16, bool includeSpecial = true) {
    const std::string lowercase = "abcdefghijklmnopqrstuvwxyz";
    const std::string uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const std::string numbers = "0123456789";
    const std::string special = "!@#$%^&*()-_=+[]{}|;:,.<>?";

    std::string chars = lowercase + uppercase + numbers;
    if (includeSpecial) {
        chars += special;
    }

    std::random_device rd;
    std::uniform_int_distribution<> distrib(0, chars.length() - 1);

    std::string password;
    password.reserve(length);

    for (int i = 0; i < length; ++i) {
        password += chars[distrib(rd)];
    }

    return password;
}

int main() {
    // Generate a 16-character password with special characters
    std::string password = generatePassword(16, true);
    std::cout << password << std::endl;  // Example: aB3$xY7!mN2@pQ9&

    // Generate a 12-character password without special characters
    std::string simplePassword = generatePassword(12, false);
    std::cout << simplePassword << std::endl;  // Example: aB3xY7mN2pQ9

    return 0;
}

How it works in C++

The function uses std::random_device directly as the engine for uniform_int_distribution, so every character comes from the platform's non-deterministic source and is uniform over the pool. Seeding std::mt19937 with one rd() call instead would cap every password at 32 bits of entropy, whatever its length.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

C++ notes

  • std::random_device is only non-deterministic where the implementation provides it: true for libstdc++ on Linux, libc++ and MSVC, not for MinGW before GCC 9.2.
  • For production code, libsodium's randombytes_uniform() or the OS call (getrandom(), BCryptGenRandom) removes that doubt.
  • Overwrite the password buffer when done; libsodium's sodium_memzero() is not optimized away like a plain memset can be.

Password Generator Code Examples in Ruby

Generate secure random passwords in Ruby using SecureRandom for cryptographically secure random generation. Perfect for Ruby on Rails applications.

require 'securerandom'

def generate_password(length = 16, include_special = true)
  lowercase = ('a'..'z').to_a
  uppercase = ('A'..'Z').to_a
  numbers = ('0'..'9').to_a
  special = '!@#$%^&*()-_=+[]{}|;:,.<>?'.chars

  chars = lowercase + uppercase + numbers
  chars += special if include_special

  Array.new(length) { chars[SecureRandom.random_number(chars.length)] }.join
end

# Generate a 16-character password with special characters
password = generate_password(16, true)
puts password  # Example: aB3$xY7!mN2@pQ9&

# Generate a 12-character password without special characters
simple_password = generate_password(12, false)
puts simple_password  # Example: aB3xY7mN2pQ9

How it works in Ruby

SecureRandom.random_number provides cryptographically secure random integers. This implementation uses Ruby's array and string manipulation methods for clean, idiomatic code.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

Ruby notes

  • Ruby 3.3+ SecureRandom.alphanumeric(16, chars: pool) builds the password from a custom pool in one call.
  • Devise checks length with config.password_length (6 to 128 by default); generate within that range.
  • Hash with has_secure_password (bcrypt gem); bcrypt uses at most 72 bytes of input, so keep generated passwords shorter than that.

Password Generator Code Examples in Go

Generate secure random passwords in Go using crypto/rand for cryptographically secure random generation. Perfect for microservices and backend systems.

package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
)

const (
    lowercase = "abcdefghijklmnopqrstuvwxyz"
    uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    numbers   = "0123456789"
    special   = "!@#$%^&*()-_=+[]{}|;:,.<>?"
)

func generatePassword(length int, includeSpecial bool) (string, error) {
    chars := lowercase + uppercase + numbers
    if includeSpecial {
        chars += special
    }

    password := make([]byte, length)
    charsLen := big.NewInt(int64(len(chars)))

    for i := 0; i < length; i++ {
        num, err := rand.Int(rand.Reader, charsLen)
        if err != nil {
            return "", err
        }
        password[i] = chars[num.Int64()]
    }

    return string(password), nil
}

func main() {
    // Generate a 16-character password with special characters
    password, _ := generatePassword(16, true)
    fmt.Println(password)  // Example: aB3$xY7!mN2@pQ9&

    // Generate a 12-character password without special characters
    simplePassword, _ := generatePassword(12, false)
    fmt.Println(simplePassword)  // Example: aB3xY7mN2pQ9
}

How it works in Go

crypto/rand.Int() provides cryptographically secure random integers. This implementation properly handles errors and uses big.Int for secure index generation within the character set range.

Sample output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

Go notes

  • crypto/rand.Int rejects out-of-range draws, so indices are uniform without manual handling.
  • Go 1.24+ crypto/rand.Text() returns a 26-character base32 secret (130 bits) for machine credentials that need no symbols.
  • Hash with golang.org/x/crypto/argon2 or bcrypt; bcrypt.GenerateFromPassword returns an error for input over 72 bytes.

Try the Interactive Generator

Need values right now rather than code? The Passwords generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE PASSWORDS GENERATOR →