Passphrase Generator Code Examples
Diceware-style passphrases in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go
Each example picks words at random from the EFF large wordlist (7,776 words) and joins them with hyphens, giving output such as crystal-thunder-freedom-mountain-velocity-quantum. The guide covers how much entropy a passphrase really has and which random source may pick the words; each language section then shows the code and what is specific to that language.
Prefer no code? The interactive Passphrases generator does the same in the browser.
Where passphrase strength comes from
The Diceware method, published by Arnold Reinhold in 1995, rolls five dice per word and looks the result up in a list of 65 = 7,776 words. The EFF large wordlist (2016) keeps that size with longer, more familiar words. Each word chosen uniformly from 7,776 adds log2(7,776) ≈ 12.9 bits of entropy, so:
- 5 words ≈ 64.6 bits
- 6 words ≈ 77.5 bits
- 7 words ≈ 90.5 bits
- 8 words ≈ 103.4 bits
These figures already assume the attacker has your wordlist and knows how many words you used. The security comes only from the random choice, never from the words being obscure. The EFF short list (1,296 words, four dice) gives about 10.3 bits per word, so it needs more words for the same strength.
How many words to use
Six words is the usual default for accounts protected by a slow server-side hash and rate limiting. A secret that can be attacked offline with no limit on guesses, such as a password manager vault, a LUKS, VeraCrypt or BitLocker volume, or an encrypted backup, is better at seven or eight words. NIST SP 800-63B asks verifiers to accept secrets of at least 64 characters, and an eight-word passphrase is usually under 60, but some sites still cap length lower, so test the field before you rely on it.
The random source picks the words, not a person
The entropy figures hold only if every word is drawn independently and uniformly by a cryptographically secure generator. A person "choosing six random words" picks related, common words, and a general-purpose PRNG such as Mersenne Twister can be reconstructed from its output or seed. Every example on this page uses the operating system CSPRNG: random_int(), crypto.getRandomValues() or crypto.randomInt(), secrets.choice(), SecureRandom, RandomNumberGenerator, std::random_device (with the caveats in the C++ section), Ruby SecureRandom and Go crypto/rand.
Draw with replacement. Removing words that were already used makes each next pick slightly weaker and buys nothing, since a repeated word is just one of 7,7766 equally likely outcomes.
Common mistakes
- Regenerating until you like the result. Rerolling until the phrase "sounds good" turns a uniform pick into a human one. Rerolling once because the phrase is hard to type costs very little; doing it twenty times costs real bits.
- Seeding a fast PRNG with a 32-bit value. A generator seeded once from a 32-bit number can only ever produce 232 different passphrases, about 32 bits, no matter how many words follow.
- Loading the wordlist file verbatim. Each line of
eff_large_wordlist.txtis11111<TAB>abacus; keep only the word, and check that the list has exactly 7,776 unique entries before using it. - Dropping the separator. Without one, "in" + "tent" and "intent" can collide. A hyphen or space removes that ambiguity and costs nothing.
- Counting decorations as strength. Capitalizing the first word or appending "1!" to satisfy a composition rule adds almost no entropy, because attackers try those variants first. Add a word instead.
Common Use Cases
- Master passwords for password managers (7–8 words)
- Full-disk and volume encryption passphrases (LUKS, BitLocker, FileVault, VeraCrypt)
- Passphrases for SSH and GPG private keys and encrypted backups
- Wi-Fi passwords that have to be read aloud or typed on a TV remote
- Memorable initial passwords for user provisioning and account recovery
Passphrase Generator Code Examples in PHP
Generate cryptographically secure, memorable passphrases in PHP using the Diceware method. Passphrases use random dictionary words for better memorability than complex passwords while maintaining high entropy.
<?php
// Diceware-style passphrase generation
function generatePassphrase(int $wordCount = 6): string {
// EFF's improved wordlist (7776 words)
$wordlist = ["ability", "able", "about", "above", "accept", /* ... 7771 more words */];
$words = [];
for ($i = 0; $i < $wordCount; $i++) {
$index = random_int(0, count($wordlist) - 1);
$words[] = $wordlist[$index];
}
return implode('-', $words);
}
// Generate 6-word passphrase (the usual Diceware/EFF default)
$passphrase = generatePassphrase(6);
echo $passphrase;
// Example: "ability-country-expand-golden-invent-rocket"
// Calculate entropy: log2(7776^6) ≈ 77.5 bits
// Stronger than most 12-character passwords
How it works in PHP
This implementation follows the Diceware method using cryptographically secure random selection. Each word is chosen from a wordlist of 7,776 words (6^5, representing 5 dice rolls). The entropy calculation shows that a 6-word passphrase provides approximately 77.5 bits of entropy, exceeding the security of most complex passwords while being significantly easier to remember and type.
Sample output
ability-country-expand-golden-invent-rocket triumph-window-justice-mountain-purple-crystal ocean-thunder-freedom-cascade-brilliant-cosmos
PHP notes
random_int($min, $max)includes both bounds, sorandom_int(0, count($wordlist) - 1)covers every index without bias.- On PHP 8.2+
random_int()throwsRandom\RandomExceptionif no secure source is available; never fall back tomt_rand(). - Load the list with
file($path, FILE_IGNORE_NEW_LINES)and split each line on the tab to drop the dice number.
Passphrase Generator Code Examples in JavaScript
Generate cryptographically secure passphrases in JavaScript using the Web Crypto API for browsers or the crypto module for Node.js. Perfect for password managers and authentication systems.
// Browser and Node.js compatible
function generatePassphrase(wordCount = 6) {
// EFF's improved wordlist (7776 words)
const wordlist = ["ability", "able", "about", "above", "accept", /* ... */];
const words = [];
const array = new Uint32Array(wordCount);
// Global in browsers, Web Workers, Deno and Node.js 19+
globalThis.crypto.getRandomValues(array);
for (let i = 0; i < wordCount; i++) {
const index = array[i] % wordlist.length;
words.push(wordlist[index]);
}
return words.join('-');
}
// Generate passphrase
console.log(generatePassphrase(6));
// "crystal-thunder-mountain-freedom-cascade-brilliant"
How it works in JavaScript
This JavaScript implementation uses the Web Crypto API for browsers and Node.js crypto module for server-side generation. The code handles both environments automatically. Using crypto.getRandomValues() ensures cryptographic quality randomness, making passphrases suitable for security-critical applications.
Sample output
crystal-thunder-mountain-freedom-cascade-brilliant jupiter-phoenix-quantum-nebula-velocity-eclipse harmony-starlight-infinite-cosmos-radiant-zenith
JavaScript notes
crypto.getRandomValues()is global in browsers, Web Workers, Deno and Node.js 19+, so one code path covers all of them.array[i] % 7776on a 32-bit value has a bias of about 1 in 550,000 per word, negligible here;crypto.randomInt(0, n)in Node.js is exactly uniform and excludesn.getRandomValues()fills at most 65,536 bytes per call, far more than a passphrase needs.
Passphrase Generator Code Examples in Python
Generate cryptographically secure passphrases in Python using the secrets module introduced in Python 3.6. The Diceware method creates memorable yet highly secure passphrases.
import secrets
def generate_passphrase(word_count=6, separator='-'):
"""Generate a Diceware-style passphrase using EFF wordlist."""
# EFF's improved wordlist (7776 words)
wordlist = ["ability", "able", "about", "above", "accept", # ... 7771 more
]
# Use secrets.choice() for cryptographic randomness
words = [secrets.choice(wordlist) for _ in range(word_count)]
return separator.join(words)
# Generate 6-word passphrase (recommended)
passphrase = generate_passphrase(6)
print(passphrase)
# Output: "galaxy-thunder-phoenix-cascade-velocity-quantum"
# Generate 8-word passphrase for higher security
strong_passphrase = generate_passphrase(8)
print(strong_passphrase)
# Output: "cosmic-mountain-radiant-freedom-nebula-infinite-crystal-harmony"
# Calculate entropy
import math
entropy = 6 * math.log2(7776)
print(f"Entropy: {entropy:.1f} bits") # 77.5 bits for 6 words
How it works in Python
Python's secrets module (Python 3.6+) draws from the operating system CSPRNG. secrets.choice() picks one word uniformly, without modulo bias, and the list comprehension repeats that for each word. Do not swap in random.choice(): the random module is a Mersenne Twister whose state can be recovered from its output. Six words from the 7,776-word list give 6 × log2(7,776) ≈ 77.5 bits.
Sample output
galaxy-thunder-phoenix-cascade-velocity-quantum cosmic-mountain-radiant-freedom-nebula-infinite starlight-harmony-eclipse-brilliant-zenith-jupiter
Python notes
secrets.choice()israndom.SystemRandom().choice()under the hood; both are safe, plainrandom.choice()is not.- Read the EFF file with
[line.split()[1] for line in open(path)]to drop the dice numbers. - The
xkcdpasspackage wraps the same idea with bundled wordlists if you prefer a dependency.
Passphrase Generator Code Examples in Java
Generate cryptographically secure passphrases in Java using SecureRandom for enterprise applications. This implementation follows the Diceware method for maximum security.
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;
public class PassphraseGenerator {
private static final List<String> WORDLIST = Arrays.asList(
"ability", "able", "about", "above", "accept" // ... 7771 more words
);
private static final SecureRandom random = new SecureRandom();
public static String generatePassphrase(int wordCount) {
StringBuilder passphrase = new StringBuilder();
for (int i = 0; i < wordCount; i++) {
if (i > 0) passphrase.append("-");
int index = random.nextInt(WORDLIST.size());
passphrase.append(WORDLIST.get(index));
}
return passphrase.toString();
}
public static void main(String[] args) {
// Generate 6-word passphrase
String passphrase = generatePassphrase(6);
System.out.println(passphrase);
// Output: "crystal-mountain-thunder-freedom-velocity-brilliant"
// Calculate entropy
double entropy = 6 * Math.log(WORDLIST.size()) / Math.log(2);
System.out.printf("Entropy: %.1f bits%n", entropy); // 77.5 bits
}
}
How it works in Java
Java's SecureRandom class provides cryptographically strong random number generation suitable for security-sensitive applications. The implementation uses a static wordlist and reuses the SecureRandom instance for performance. This approach is thread-safe and suitable for enterprise web applications.
Sample output
crystal-mountain-thunder-freedom-velocity-brilliant phoenix-quantum-nebula-cascade-harmony-infinite cosmos-radiant-jupiter-starlight-eclipse-zenith
Java notes
SecureRandom.nextInt(bound)excludesboundand is unbiased; one shared instance is thread-safe.- Plain
new SecureRandom()is the right choice, including on Android;getInstanceStrong()can block on some Linux JDKs and adds nothing for this use. - Load the list with
Files.readAllLines()or from a classpath resource and join withString.join("-", words).
Passphrase Generator Code Examples in C#
Generate cryptographically secure passphrases in C# using RandomNumberGenerator for .NET applications. Perfect for ASP.NET Core identity systems.
using System;
using System.Security.Cryptography;
using System.Linq;
public class PassphraseGenerator
{
private static readonly string[] Wordlist = new[]
{
"ability", "able", "about", "above", "accept" // ... 7771 more words
};
public static string GeneratePassphrase(int wordCount = 6)
{
using var rng = RandomNumberGenerator.Create();
var words = new string[wordCount];
for (int i = 0; i < wordCount; i++)
{
byte[] randomBytes = new byte[4];
rng.GetBytes(randomBytes);
uint randomValue = BitConverter.ToUInt32(randomBytes, 0);
int index = (int)(randomValue % Wordlist.Length);
words[i] = Wordlist[index];
}
return string.Join("-", words);
}
public static void Main()
{
// Generate 6-word passphrase
string passphrase = GeneratePassphrase(6);
Console.WriteLine(passphrase);
// Output: "thunder-crystal-freedom-mountain-quantum-brilliant"
// Calculate entropy: log2(7776^6) ≈ 77.5 bits
double entropy = 6 * Math.Log(Wordlist.Length, 2);
Console.WriteLine($"Entropy: {entropy:F1} bits");
}
}
How it works in C#
C#'s RandomNumberGenerator class provides cryptographically secure random number generation. This implementation uses proper disposal patterns with using statements. The modulo operation introduces negligible bias with 32-bit random values. This approach is suitable for ASP.NET Core applications and Windows desktop applications.
Sample output
thunder-crystal-freedom-mountain-quantum-brilliant phoenix-nebula-velocity-cascade-harmony-infinite starlight-cosmos-radiant-eclipse-jupiter-zenith
C# notes
RandomNumberGenerator.GetInt32(toExclusive)(.NET Core 3.0+) returns an unbiased index without manual byte handling.- On .NET 8+,
RandomNumberGenerator.GetItems(wordlist, 6)picks the words in one call. - The static
RandomNumberGeneratormethods are thread-safe and need nousingor disposal.
Passphrase Generator Code Examples in C++
Generate cryptographically secure passphrases in C++ using modern C++11/14 random number facilities. This implementation uses std::random_device for entropy.
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
class PassphraseGenerator {
private:
std::vector<std::string> wordlist = {
"ability", "able", "about", "above", "accept" // ... 7771 more
};
std::random_device rd;
public:
std::string generate(int wordCount = 6) {
std::uniform_int_distribution<> dist(0, wordlist.size() - 1);
std::vector<std::string> words;
words.reserve(wordCount);
for (int i = 0; i < wordCount; ++i) {
words.push_back(wordlist[dist(rd)]);
}
// Join words with hyphens
std::string result;
for (size_t i = 0; i < words.size(); ++i) {
if (i > 0) result += "-";
result += words[i];
}
return result;
}
};
int main() {
PassphraseGenerator generator;
// Generate 6-word passphrase
std::string passphrase = generator.generate(6);
std::cout << passphrase << std::endl;
// Output: "crystal-thunder-mountain-freedom-velocity-quantum"
return 0;
}
How it works in C++
The example draws every index directly from std::random_device through std::uniform_int_distribution, which maps the raw values onto the wordlist range without modulo bias. It does not seed std::mt19937 first: a Mersenne Twister seeded with one 32-bit value can only produce 232 different passphrases, about 32 bits of entropy instead of 77.5. Calling the device once per word is slower, which does not matter for six words.
Sample output
crystal-thunder-mountain-freedom-velocity-quantum phoenix-nebula-cascade-brilliant-harmony-infinite cosmos-radiant-starlight-jupiter-eclipse-zenith
C++ notes
- The C++ standard allows
std::random_deviceto be deterministic; libstdc++ on Linux, libc++ and MSVC read the OS source, but MinGW before GCC 9.2 returned a fixed sequence. - When you must be certain, use the OS directly (
getrandom(),BCryptGenRandom) or libsodiumrandombytes_uniform(7776). std::random_device::entropy()is not a reliable test; some implementations return 0 even for secure sources.
Passphrase Generator Code Examples in Ruby
Generate cryptographically secure passphrases in Ruby using SecureRandom. Perfect for Rails applications and user authentication systems.
require 'securerandom'
class PassphraseGenerator
WORDLIST = %w[
ability able about above accept
].freeze # ... plus 7771 more words in the real list
def self.generate(word_count: 6, separator: '-')
words = Array.new(word_count) do
WORDLIST[SecureRandom.random_number(WORDLIST.length)]
end
words.join(separator)
end
def self.entropy(word_count: 6)
# Entropy = log2(7776^word_count)
word_count * Math.log2(WORDLIST.length)
end
end
# Generate 6-word passphrase
passphrase = PassphraseGenerator.generate(word_count: 6)
puts passphrase
# Output: "crystal-thunder-freedom-mountain-velocity-quantum"
# Generate 7-word passphrase for higher security
strong = PassphraseGenerator.generate(word_count: 7)
puts strong
# Show entropy
puts "Entropy: #{PassphraseGenerator.entropy(word_count: 6).round(1)} bits"
# Output: Entropy: 77.5 bits
How it works in Ruby
Ruby's SecureRandom module provides cryptographically strong random number generation using the operating system's secure random facilities. This implementation is idiomatic Ruby with class methods for easy usage. The code is thread-safe and suitable for Rails applications.
Sample output
crystal-thunder-freedom-mountain-velocity-quantum phoenix-nebula-cascade-brilliant-harmony-infinite cosmos-radiant-starlight-jupiter-eclipse-zenith
Ruby notes
SecureRandom.random_number(n)returns 0 to n−1;WORDLIST.sample(random: SecureRandom)does the same pick in one call.- A
#inside%w[...]is not a comment: it becomes a word in the array, so keep comments outside the literal. - Load the list with
File.readlines(path, chomp: true).map { _1.split("\t").last }.
Passphrase Generator Code Examples in Go
Generate cryptographically secure passphrases in Go using crypto/rand for microservices and backend systems. Idiomatic Go implementation of the Diceware method.
package main
import (
"crypto/rand"
"fmt"
"math/big"
"strings"
)
var wordlist = []string{
"ability", "able", "about", "above", "accept", // ... 7771 more words
}
func GeneratePassphrase(wordCount int) (string, error) {
words := make([]string, wordCount)
max := big.NewInt(int64(len(wordlist)))
for i := 0; i < wordCount; i++ {
n, err := rand.Int(rand.Reader, max)
if err != nil {
return "", fmt.Errorf("random generation failed: %w", err)
}
words[i] = wordlist[n.Int64()]
}
return strings.Join(words, "-"), nil
}
func main() {
// Generate 6-word passphrase
passphrase, err := GeneratePassphrase(6)
if err != nil {
panic(err)
}
fmt.Println(passphrase)
// Output: "crystal-thunder-freedom-mountain-velocity-quantum"
// Generate multiple passphrases
for i := 0; i < 3; i++ {
p, _ := GeneratePassphrase(6)
fmt.Println(p)
}
}
How it works in Go
Go's crypto/rand package provides cryptographically secure random number generation using the operating system's CSPRNG. This implementation follows Go conventions with proper error handling. The use of big.Int ensures unbiased random selection across the wordlist.
Sample output
crystal-thunder-freedom-mountain-velocity-quantum phoenix-nebula-cascade-brilliant-harmony-infinite cosmos-radiant-starlight-jupiter-eclipse-zenith
Go notes
crypto/rand.Int(rand.Reader, max)returns a uniform*big.Intin [0, max), so there is no modulo bias.- Since Go 1.24,
rand.Readnever returns an error (it crashes the program instead); keep checking the error fromrand.Intas the example does. - Ship the wordlist inside the binary with
//go:embed eff_large_wordlist.txt(Go 1.16+).
Try the Interactive Generator
Need values right now rather than code? The Passphrases generator runs in the browser and exports to TXT, CSV or JSON.
OPEN THE PASSPHRASES GENERATOR →