🔑 Security

Password Generation Code Examples — Secure Random Passwords

Copy-paste secure password generation examples for JavaScript, Python, Go, Bash, TypeScript, and cURL. Cryptographically secure random passwords ready for production.

Generate a Secure Random Password in JavaScript

javascript

Use the Web Crypto API to generate cryptographically secure random passwords in the browser or Node.js.

// Browser & Node.js 19+
function generatePassword(length = 16) {
  const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
  const values = crypto.getRandomValues(new Uint32Array(length));
  return Array.from(values, v => charset[v % charset.length]).join('');
}

console.log(generatePassword());    // e.g. "kR7#mP2xLq9&wN4f"
console.log(generatePassword(24));  // e.g. "Tz5!bQ8vXj3#nG6yHw1$mK4r"
console.log(generatePassword(8));   // e.g. "Jx3$pL7m"

Generate a Passphrase in JavaScript

javascript

Create memorable but secure passphrases using random words (Diceware-style).

// Simple passphrase generator (browser/Node.js)
const words = [
  'apple', 'brave', 'crane', 'delta', 'eagle', 'frost',
  'grain', 'hatch', 'ivory', 'joust', 'kneel', 'lemon',
  'maple', 'noble', 'ocean', 'plaza', 'quest', 'ridge',
  'solar', 'torch', 'unity', 'vivid', 'waltz', 'xenon',
  'yield', 'zesty', 'amber', 'blaze', 'coral', 'drift'
];

function generatePassphrase(wordCount = 4, separator = '-') {
  const values = crypto.getRandomValues(new Uint32Array(wordCount));
  return Array.from(values, v => words[v % words.length]).join(separator);
}

console.log(generatePassphrase());      // e.g. "coral-torch-maple-quest"
console.log(generatePassphrase(5, ' ')); // e.g. "noble ocean drift solar crane"

Generate a Secure Password in Python

python

Use the secrets module (Python 3.6+) for cryptographically strong random passwords.

import secrets
import string

def generate_password(length=16):
    """Generate a cryptographically secure random password."""
    charset = string.ascii_letters + string.digits + "!@#$%^&*"
    return ''.join(secrets.choice(charset) for _ in range(length))

print(generate_password())     # e.g. "kR7#mP2xLq9&wN4f"
print(generate_password(24))   # e.g. "Tz5!bQ8vXj3#nG6yHw1$mK4r"

# Ensure password meets complexity requirements
def generate_strong_password(length=16):
    while True:
        pwd = generate_password(length)
        if (any(c.isupper() for c in pwd)
                and any(c.islower() for c in pwd)
                and any(c.isdigit() for c in pwd)
                and any(c in '!@#$%^&*' for c in pwd)):
            return pwd

print(generate_strong_password())  # Guaranteed complex

Generate a Passphrase in Python

python

Create a Diceware-style passphrase using the secrets module.

import secrets

# Simple word list (use a full Diceware list for production)
WORDS = [
    'apple', 'brave', 'crane', 'delta', 'eagle', 'frost',
    'grain', 'hatch', 'ivory', 'joust', 'kneel', 'lemon',
    'maple', 'noble', 'ocean', 'plaza', 'quest', 'ridge',
    'solar', 'torch', 'unity', 'vivid', 'waltz', 'xenon',
]

def generate_passphrase(word_count=4, separator='-'):
    return separator.join(secrets.choice(WORDS) for _ in range(word_count))

print(generate_passphrase())        # e.g. "crane-solar-noble-frost"
print(generate_passphrase(5, ' '))  # e.g. "maple ocean torch eagle brave"

# Built-in token generators
print(secrets.token_hex(16))        # 32 hex chars
print(secrets.token_urlsafe(16))    # 22 URL-safe chars

Generate a Secure Password in TypeScript

typescript

Type-safe password generation using the Web Crypto API with configurable character sets.

interface PasswordOptions {
  length: number;
  uppercase: boolean;
  lowercase: boolean;
  digits: boolean;
  symbols: boolean;
}

function generatePassword(options: Partial<PasswordOptions> = {}): string {
  const opts: PasswordOptions = {
    length: 16,
    uppercase: true,
    lowercase: true,
    digits: true,
    symbols: true,
    ...options,
  };

  let charset = '';
  if (opts.uppercase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  if (opts.lowercase) charset += 'abcdefghijklmnopqrstuvwxyz';
  if (opts.digits) charset += '0123456789';
  if (opts.symbols) charset += '!@#$%^&*';

  const values = crypto.getRandomValues(new Uint32Array(opts.length));
  return Array.from(values, (v) => charset[v % charset.length]).join('');
}

console.log(generatePassword());                    // Full charset
console.log(generatePassword({ length: 32 }));      // Longer
console.log(generatePassword({ symbols: false }));   // No symbols

Generate a Secure Password in Go

go

Use crypto/rand for cryptographically secure password generation in Go.

package main

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

func generatePassword(length int) (string, error) {
    charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*"
    result := make([]byte, length)
    for i := range result {
        idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
        if err != nil {
            return "", err
        }
        result[i] = charset[idx.Int64()]
    }
    return string(result), nil
}

func main() {
    pwd, err := generatePassword(16)
    if err != nil {
        panic(err)
    }
    fmt.Println(pwd) // e.g. "kR7#mP2xLq9&wN4f"

    // Generate a 32-char password
    long, _ := generatePassword(32)
    fmt.Println(long)
}

Generate Passwords in Bash (CLI)

bash

Generate random passwords using command-line tools available on Linux and macOS.

# Using /dev/urandom (Linux & macOS)
head -c 32 /dev/urandom | base64 | tr -d '=/+' | head -c 16
# Output: e.g. "kR7mP2xLq9wN4fTz"

# Using openssl
openssl rand -base64 24 | tr -d '=/+' | head -c 16
# Output: e.g. "Tz5bQ8vXj3nG6yHw"

# Alphanumeric + symbols (Linux)
tr -dc 'A-Za-z0-9!@#$%^&*' < /dev/urandom | head -c 16
# Output: e.g. "Jx3$pL7m&Kw2!Rn9"

# Generate multiple passwords
for i in $(seq 5); do
  openssl rand -base64 24 | tr -d '=/+' | head -c 16
  echo
done

# macOS: copy to clipboard
openssl rand -base64 24 | tr -d '=/+' | head -c 16 | pbcopy
echo "Password copied to clipboard"

Generate Passwords via API with cURL

bash

Use cURL with random.org API or generate locally with openssl.

# Generate a random password locally with openssl + base64
curl -s "data:text/plain;base64,$(openssl rand -base64 24)" | head -c 16

# Quick one-liner: generate and display
openssl rand -base64 24 | cut -c1-16
# Output: e.g. "Tz5bQ8vXj3nG6yHw"

# Generate a hex token (useful for API keys)
openssl rand -hex 32
# Output: 64 hex characters

# Generate a URL-safe token
python3 -c "import secrets; print(secrets.token_urlsafe(24))"
# Output: e.g. "Kj7_mR2xLq9-wN4fTz5bQ8vX"

Generate a Secure Password in Java

java

Use java.security.SecureRandom for cryptographically secure password generation.

import java.security.SecureRandom;

public class PasswordGenerator {
    private static final String CHARSET =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";

    public static String generate(int length) {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(CHARSET.charAt(random.nextInt(CHARSET.length())));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(generate(16)); // e.g. "kR7#mP2xLq9&wN4f"
        System.out.println(generate(32)); // Longer password
    }
}

Generate a Secure Password in Rust

rust

Use the rand crate with OsRng for cryptographically secure password generation.

// Cargo.toml: rand = "0.8"
use rand::Rng;

fn generate_password(length: usize) -> String {
    let charset: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
    let mut rng = rand::thread_rng();
    (0..length)
        .map(|_| charset[rng.gen_range(0..charset.len())] as char)
        .collect()
}

fn main() {
    println!("{}", generate_password(16)); // e.g. "kR7#mP2xLq9&wN4f"
    println!("{}", generate_password(32)); // Longer password
}

Generate a Secure Password in C#

csharp

Use System.Security.Cryptography for secure password generation in .NET.

using System.Security.Cryptography;

string GeneratePassword(int length = 16)
{
    const string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
    var result = new char[length];
    for (int i = 0; i < length; i++)
    {
        result[i] = charset[RandomNumberGenerator.GetInt32(charset.Length)];
    }
    return new string(result);
}

Console.WriteLine(GeneratePassword());    // e.g. "kR7#mP2xLq9&wN4f"
Console.WriteLine(GeneratePassword(32));  // Longer password

Password Strength & Entropy Reference

text

Quick reference for password strength by length and character set.

Length  Charset               Entropy (bits)   Time to Crack*
------  -------               --------------   --------------
8       lowercase (26)         37.6             Seconds
8       mixed case (52)        45.6             Hours
8       + digits (62)          47.6             Hours
8       + symbols (72)         49.2             Days
12      mixed+digits (62)      71.5             Centuries
16      mixed+digits (62)      95.3             Heat death
16      + symbols (72)         98.6             Heat death
20      mixed+digits (62)      119.1            Heat death

* Estimated at 1 trillion guesses/second.

RECOMMENDATIONS:
- Minimum 12 characters for user passwords
- Minimum 16 characters for admin/service accounts
- Use passphrases (4+ random words) for memorability
- Always use a password manager
- Never reuse passwords across services
- Enable 2FA/MFA whenever available

Need to work with generate secure passwords right now?

Use our free online password generator — no signup, no install, works in your browser.

Open Password Generator →

More Code Snippets