Random Password Generator
Generate cryptographically secure random passwords with customizable length, symbols, and ambiguous character filters.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
Information Theory & Cryptographic Randomness
A Random Password Generator synthesizes high-entropy, computationally unpredictable character sequences designed to secure authentication credentials, cryptographic passphrases, API tokens, and administrative secrets. The mathematical foundation of password resilience is defined by Claude Shannon's concept of Information Entropy:
$$H = L \times \log_2(N)$$
Where:
- $H$ represents the total entropy of the generated secret expressed in bits.
- $L$ represents the total character length of the password.
- $N$ represents the size of the symbol pool from which characters are chosen (the alphabet cardinality).
+---------------------------------------------------------------------------------------------------+
| ENTROPY GENERATION ARCHITECTURAL FLOW |
+---------------------------------------------------------------------------------------------------+
| KERNEL HARDWARE ENTROPY CSPRNG ALGORITHM REJECTION SAMPLING|
| - Thermal Jitter (CPU RDRAND) - Linux: getrandom() / urandom - Eliminates Modulo|
| - Interrupt Timings --> - Windows: BCryptGenRandom --> Bias |
| - Disk / Network Noise - Web Crypto: getRandomValues() - Uniform Selection|
+---------------------------------------------------------------------------------------------------+
|
v
+---------------------------------------------------------------------------------------------------+
| HIGH-ENTROPY CRYPTOGRAPHIC SECRET |
| Length: 20 characters | Pool: 94 ASCII symbols | Entropy: 131.08 bits |
| Brute-force resilience: > 10^21 GPU-years against state-level cracking clusters |
+---------------------------------------------------------------------------------------------------+
The Catastrophic Hazard of Math.random()
A critical vulnerability in poorly engineered web utilities is relying on standard pseudo-random number generators (PRNGs) such as JavaScript's Math.random(), Python's random module, or C's rand().
- Deterministic Internal State: Standard PRNGs are driven by algorithms like xorshift128+ or the Mersenne Twister (MT19937). These algorithms are optimized for game mechanics and Monte Carlo simulations, not information security.
- State Recovery Attacks: Because the internal state of a Mersenne Twister consists of only 624 32-bit integers, observing just 624 consecutive outputs allows an attacker to completely reconstruct the generator's internal state matrix. An adversary can then retroactively calculate past passwords or predict every future secret generated by the application.
- Cryptographically Secure PRNG (CSPRNG): Secure generators interface directly with kernel-level entropy pools seeded by non-deterministic physical phenomena (CPU thermal jitter, hardware interrupts, keystroke timings, and network packet arrivals). CSPRNGs satisfy the Next-Bit Test: given the first $k$ bits of a random sequence, no polynomial-time algorithm can predict the $(k+1)$-th bit with probability greater than $0.5 + \epsilon$.
Character Space Sets & Entropy Formulas Matrix
The size of the candidate character pool directly establishes the base entropy per symbol:
+---------------------------------------------------------------------------------------------------+
| ALPHABET POOL ENTROPY SPECTRUM |
+---------------------------------------------------------------------------------------------------+
| Character Set Configuration Pool Symbols Included Pool Size (N) Bits / Char |
| ------------------------------------ ---------------------------- ------------- ------------ |
| Numeric Digits Only 0 - 9 10 3.32 bits |
| Lowercase Latin Letters a - z 26 4.70 bits |
| Alphanumeric (Lower + Upper + Digits) a-z, A-Z, 0-9 62 5.95 bits |
| Full Printable ASCII Symbols Alphanumeric + !@#$%^&*... 94 6.55 bits |
| Unambiguous Human-Safe Set Excludes 0, O, o, 1, l, I, | 74 6.21 bits |
+---------------------------------------------------------------------------------------------------+
Mathematical Example: Comparing Password Profiles
- Profile A (8-character lowercase): $$H = 8 \times \log_2(26) = 8 \times 4.70 = \mathbf{37.60 \text{ bits}}$$ Search Space: $26^8 \approx 2.08 \times 10^{11}$ combinations. Can be cracked in under 10 milliseconds on a modern multi-GPU rig.
- Profile B (16-character alphanumeric): $$H = 16 \times \log_2(62) = 16 \times 5.95 = \mathbf{95.27 \text{ bits}}$$ Search Space: $62^{16} \approx 4.76 \times 10^{28}$ combinations. Requires millions of years against distributed offline dictionary and brute-force attacks.
- Profile C (24-character full ASCII): $$H = 24 \times \log_2(94) = 24 \times 6.55 = \mathbf{157.31 \text{ bits}}$$ Search Space: Exceeds the estimated number of atoms in the observable universe, delivering complete cryptographic immunity against classical supercomputing clusters.
Production Code Implementation
Python: Cryptographically Sound Generator with Rejection Sampling
Python's secrets module (PEP 506) wraps operating system CSPRNG primitives (os.urandom()). The implementation below demonstrates uniform rejection sampling to eliminate modulo bias.
#!/usr/bin/env python3
"""
Industrial Random Password Generator with Zero Modulo Bias,
Configurable Character Pools, and Shannon Entropy Auditing.
"""
import math
import secrets
import string
from typing import Set, Tuple
class CryptographicPasswordGenerator:
# Ambiguous characters frequently misread on mobile screens or paper backups
AMBIGUOUS_CHARACTERS: Set[str] = {"0", "O", "o", "1", "l", "I", "|", "`", "'", "\"", ";", ":"}
def __init__(
self,
use_lowercase: bool = True,
use_uppercase: bool = True,
use_digits: bool = True,
use_symbols: bool = True,
exclude_ambiguous: bool = True,
):
pool = ""
if use_lowercase:
pool += string.ascii_lowercase
if use_uppercase:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_symbols:
pool += "!@#$%^&*()-_=+[]{}|;:,.<>?"
if exclude_ambiguous:
pool = "".join(ch for ch in pool if ch not in self.AMBIGUOUS_CHARACTERS)
if not pool:
raise ValueError("Character pool cannot be empty. Enable at least one character set.")
self.pool = pool
self.pool_size = len(pool)
self.bits_per_char = math.log2(self.pool_size)
def generate(self, length: int = 20) -> Tuple[str, float]:
"""
Generates a password using rejection sampling to guarantee uniform distribution.
Returns the password string and its Shannon entropy in bits.
"""
if length < 8:
raise ValueError("Password length must be at least 8 characters.")
# Rejection sampling threshold: largest multiple of pool_size fitting in a 256-value byte
limit = 256 - (256 % self.pool_size)
chars = []
while len(chars) < length:
# Fetch cryptographically secure random bytes
random_bytes = secrets.token_bytes(length - len(chars) + 8)
for byte in random_bytes:
if byte < limit:
chars.append(self.pool[byte % self.pool_size])
if len(chars) == length:
break
password = "".join(chars)
total_entropy = length * self.bits_per_char
return password, round(total_entropy, 2)
# Demonstration
if __name__ == "__main__":
generator = CryptographicPasswordGenerator(
use_lowercase=True,
use_uppercase=True,
use_digits=True,
use_symbols=True,
exclude_ambiguous=True,
)
pwd, entropy = generator.generate(length=24)
print("--- CRYPTOGRAPHIC PASSWORD GENERATOR ---")
print(f"Generated Password: {pwd}")
print(f"Character Pool Size: {generator.pool_size} glyphs")
print(f"Calculated Entropy: {entropy} bits")
TypeScript: Web Crypto API Implementation for Frontend Applications
/**
* Browser-native Web Crypto API Password Generator
* Guarantees zero network transmission and CSPRNG uniform sampling.
*/
export interface GeneratorOptions {
length: number;
includeUpper?: boolean;
includeLower?: boolean;
includeNumbers?: boolean;
includeSymbols?: boolean;
excludeAmbiguous?: boolean;
}
export function generateSecurePassword(options: GeneratorOptions): {
password: string;
entropyBits: number;
} {
const {
length,
includeUpper = true,
includeLower = true,
includeNumbers = true,
includeSymbols = true,
excludeAmbiguous = true,
} = options;
let pool = "";
if (includeLower) pool += "abcdefghijklmnopqrstuvwxyz";
if (includeUpper) pool += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (includeNumbers) pool += "0123456789";
if (includeSymbols) pool += "!@#$%^&*()-_=+[]{}<>,.?";
if (excludeAmbiguous) {
const ambiguous = new Set(["0", "O", "o", "1", "l", "I", "|"]);
pool = pool.split("").filter(ch => !ambiguous.has(ch)).join("");
}
if (pool.length === 0) {
throw new Error("Character pool cannot be empty.");
}
const poolSize = pool.length;
const maxByte = 256 - (256 % poolSize);
const result: string[] = [];
while (result.length < length) {
const randomBuffer = new Uint8Array(length * 2);
crypto.getRandomValues(randomBuffer);
for (let i = 0; i < randomBuffer.length; i++) {
const val = randomBuffer[i];
if (val < maxByte) {
result.push(pool[val % poolSize]);
if (result.length === length) break;
}
}
}
const entropyBits = length * Math.log2(poolSize);
return {
password: result.join(""),
entropyBits: Math.round(entropyBits * 100) / 100,
};
}
Password Security & Offline Cracking Feasibility Matrix
The table below illustrates brute-force search horizons against an enterprise cracking array capable of computing $10^{11}$ fast hashes (NTLM/MD5) or $10^5$ memory-hard hashes (Argon2id/bcrypt) per second:
| Password Configuration | Pool Size ($N$) | Total Entropy ($H$) | Feasibility: Fast Hash (NTLM / MD5) | Feasibility: Slow Hash (Argon2id / bcrypt) |
|---|---|---|---|---|
| 8 Chars (Lowercase) | 26 | 37.6 bits | < 10 Milliseconds (Instant) | ~2.4 Days |
| 8 Chars (Full ASCII) | 94 | 52.4 bits | ~1.7 Hours | ~1,900 Years |
| 12 Chars (Alphanumeric) | 62 | 71.4 bits | ~102 Years | Completely Infeasible ($> 10^8$ Years) |
| 16 Chars (Full ASCII) | 94 | 104.9 bits | $> 10^{13}$ Years (Unhackable) | Permanently Infeasible |
| 20 Chars (Full ASCII) | 94 | 131.1 bits | Exceeds Lifespan of Universe | Beyond Theoretical Physics Limits |
Critical Traps & Security Edge Cases
1. The Modulo Bias Vulnerability
A widespread mathematical flaw in amateur password generators is naive modulo arithmetic:
// FLAWED IMPLEMENTATION: Introduces Modulo Bias!
const char = pool[randomByte % pool.length];
A single random byte yields values from $0$ to $255$ ($256$ possible values). If pool.length is $94$, $256 \div 94 = 2$ with a remainder of $68$.
- The first $68$ characters in the pool have a probability of $3/256 \approx 1.17%$.
- The remaining $26$ characters have a probability of only $2/256 \approx 0.78%$.
- This skew reduces overall entropy and creates subtle statistical vulnerabilities that dictionary crackers exploit.
- Remediation: Always use Rejection Sampling (discarding bytes $\ge 256 - (256 \bmod \text{pool_length})$) to ensure exact mathematical uniformity across all characters.
2. Post-Generation Constraint Injections (Entropy Reduction)
Some systems force compliance rules (e.g., "Must contain at least 1 digit and 1 symbol") by generating a random string and then manually replacing the first character with a symbol and the second with a digit.
- Overwriting fixed indices leaks structural information to attackers, degrading password entropy by eliminating randomness at those specific positions.
- Remediation: If specific character categories must be guaranteed, select one random symbol from each required subset, fill the remaining positions from the combined pool, and execute a cryptographically secure Fisher-Yates shuffle over the entire array.
3. Clipboard Leaks and Memory Exposure
Client-side password generators that offer a "Copy to Clipboard" button must manage memory lifecycles responsibly:
- Once copied, the plaintext secret resides in the operating system clipboard buffer, accessible to unauthorized background processes or browser extensions.
- Web applications should provide an ephemeral clipboard wipe timeout (clearing the clipboard after 30 or 60 seconds) and set
autocomplete="new-password"andspellcheck="false"on all input fields to prevent browser memory caches from logging sensitive credentials.