Building a Cryptographically Secure Password Generator in C# .NET



This content originally appeared on DEV Community and was authored by Bayron Rodezno

How I created an open-source tool that goes beyond basic randomization to ensure real password security

Password Security Header

🔐 The Password Problem We All Ignore

Let’s be honest: most of us have used “Password123!” at least once. Even worse, many password generators out there are doing the bare minimum—creating random strings without considering the sophisticated attacks that exist today.

After seeing countless data breaches and weak password implementations, I decided to build something different: a cryptographically secure password generator that doesn’t just create random strings, but actively prevents common attack vectors.

The result? An open-source C# .NET application that’s now available on GitHub with MIT license.

🔗 Check it out here: github.com/brodznodev/password-generator-net

🎯 What Makes a Password Generator “Secure”?

Before diving into the code, let’s understand what separates a truly secure password generator from a basic one:

❌ What Most Generators Do Wrong:

  • Use Random() class (predictable pseudo-random)
  • Don’t validate against common patterns
  • Allow sequential characters (abc, 123, qwerty)
  • Ignore dictionary words and common passwords
  • No strength analysis or feedback

✅ What Real Security Requires:

  • Cryptographic randomness using RandomNumberGenerator
  • Pattern detection to avoid predictable sequences
  • Dictionary validation against common passwords
  • Repetition control to prevent character clustering
  • Comprehensive strength analysis with actionable feedback

🧠 The Architecture: Security by Design

I structured the project with three main components, each with a specific security responsibility:

📁 Project Structure
├── Program.cs              // Interactive CLI interface
├── PasswordGenerator.cs    // Core generation logic
└── PasswordValidator.cs    // Strength analysis & validation

Separation of Concerns:

  • Generation: Creates cryptographically random passwords
  • Validation: Analyzes and scores password strength
  • Interface: Provides user-friendly interaction

This architecture ensures that security logic is isolated and testable.

🔬 Deep Dive: The Generation Algorithm

Step 1: Character Set Definition

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

    // Total entropy: 92 unique characters
}

Why these specific characters?

  • Maximum compatibility: Works across platforms and systems
  • High entropy: 92 possible characters per position
  • Visual distinction: Easy to differentiate when typing
  • Special character variety: Meets most complexity requirements

Step 2: Cryptographic Random Generation

This is where most generators fail. Here’s the secure approach:

private static string CreateRandomPassword(int length)
{
    using (var rng = RandomNumberGenerator.Create())
    {
        var password = new StringBuilder();
        var allChars = Lowercase + Uppercase + Numbers + SpecialCharacters;

        // Guarantee at least one character from each category
        password.Append(GetRandomCharFromString(Lowercase, rng));
        password.Append(GetRandomCharFromString(Uppercase, rng));
        password.Append(GetRandomCharFromString(Numbers, rng));
        password.Append(GetRandomCharFromString(SpecialCharacters, rng));

        // Fill remaining positions with random characters
        for (int i = 4; i < length; i++)
        {
            password.Append(GetRandomCharFromString(allChars, rng));
        }

        // Cryptographically secure shuffle
        return ShuffleString(password.ToString(), rng);
    }
}

Key Security Features:

  1. RandomNumberGenerator: Uses OS entropy, not predictable algorithms
  2. Guaranteed diversity: Ensures all character types are present
  3. Secure shuffling: Prevents position-based patterns
  4. Proper disposal: Uses using statement for resource management

Step 3: The Secure Shuffle Algorithm

private static string ShuffleString(string input, RandomNumberGenerator rng)
{
    var chars = input.ToCharArray();

    // Fisher-Yates shuffle with cryptographic randomness
    for (int i = chars.Length - 1; i > 0; i--)
    {
        byte[] randomBytes = new byte[4];
        rng.GetBytes(randomBytes);
        int randomIndex = Math.Abs(BitConverter.ToInt32(randomBytes, 0)) % (i + 1);

        // Swap characters
        (chars[i], chars[randomIndex]) = (chars[randomIndex], chars[i]);
    }

    return new string(chars);
}

Why Fisher-Yates? It’s mathematically proven to produce uniform random permutations when given a proper random source.

🛡 Security Validations: Beyond Basic Checks

The validator doesn’t just check “has uppercase, lowercase, numbers”—it actively hunts for weakness patterns:

Pattern Detection System

// Common password patterns to avoid
private static readonly HashSet<string> CommonPasswords = new HashSet<string>
{
    "password", "123456", "qwerty", "admin", "letmein", "welcome",
    "monkey", "dragon", "password1", "123456789", "football",
    "iloveyou", "admin123", "master", "sunshine", "princess"
};

// Sequential patterns that indicate weak generation
private static readonly string[] SequentialPatterns = 
{
    "abc", "bcd", "cde", "def", "efg", "fgh", "ghi", "hij", "ijk",
    "123", "234", "345", "456", "567", "678", "789", "890",
    "qwe", "wer", "ert", "rty", "tyu", "yui", "uio", "iop",
    "asd", "sdf", "dfg", "fgh", "ghj", "hjk", "jkl",
    "zxc", "xcv", "cvb", "vbn", "bnm"
};

Advanced Repetition Detection

private static bool HasRepeatingCharacters(string password, int maxRepeats)
{
    for (int i = 0; i <= password.Length - maxRepeats; i++)
    {
        char currentChar = password[i];
        int consecutiveCount = 1;

        for (int j = i + 1; j < password.Length; j++)
        {
            if (password[j] == currentChar)
            {
                consecutiveCount++;
                if (consecutiveCount >= maxRepeats)
                    return true;
            }
            else break;
        }
    }
    return false;
}

This catches patterns like “aaa123” or “password111” that would bypass basic validation.

📊 The Scoring System: Quantifying Password Strength

I developed a comprehensive scoring system that provides actionable feedback:

private static int CalculateStrengthScore(string password)
{
    int score = 0;

    // Base points for length (up to 50 points)
    score += Math.Min(password.Length * 2, 50);

    // Character variety bonuses
    if (password.Any(char.IsLower)) score += 10;      // Lowercase
    if (password.Any(char.IsUpper)) score += 10;      // Uppercase
    if (password.Any(char.IsDigit)) score += 10;      // Numbers
    if (password.Any(c => "!@#$%^&*()_+-=[]{}|;':\",./<>?".Contains(c))) 
        score += 15;  // Special characters

    // Complexity bonuses
    if (password.Length > 16) score += 10;            // Extra length
    if (HasComplexPatterns(password)) score += 5;     // Advanced patterns

    // Security penalties
    if (ContainsCommonPatterns(password)) score -= 20; // Common patterns
    if (HasExcessiveRepeatingChars(password)) score -= 15; // Repetitions

    return Math.Max(0, Math.Min(100, score));
}

Strength Classification

Score Range Level Description
80-100 🟢 Very Strong Excellent entropy, no detectable patterns
60-79 🔵 Strong Good security, minor improvements possible
40-59 🟡 Medium Adequate but could be stronger
20-39 🟠 Weak Vulnerable to common attacks
0-19 🔴 Very Weak Easily compromised

🎮 User Experience: Making Security Accessible

Security tools are only effective if people actually use them. I designed an intuitive CLI interface:

🔐 GENERADOR DE CONTRASEÑAS SEGURAS
═══════════════════════════════════════

🎯 ¿Qué deseas hacer?
1. Generar una contraseña segura
2. Generar múltiples contraseñas  
3. Validar una contraseña existente
4. Ver consejos de seguridad
5. Salir

Real-time Feedback

When you generate a password, you get immediate analysis:

🎉 Contraseña generada: K7@mP9#vQ2$nX8wR

🔍 ANÁLISIS DE FORTALEZA DE CONTRASEÑA
═══════════════════════════════════════
Contraseña: K7@mP9#vQ2$nX8wR
Longitud: 16 caracteres

📋 Criterios de Validación:
   ✓ Longitud mínima (12+): ✅
   ✓ Mayúsculas: ✅
   ✓ Minúsculas: ✅
   ✓ Números: ✅
   ✓ Caracteres especiales: ✅
   ✓ Sin patrones comunes: ✅
   ✓ Sin repeticiones excesivas: ✅

📊 Puntuación: 95/100
🎯 Nivel de Fortaleza: 🟢 MUY FUERTE
🛡 Estado: ✅ VÁLIDA

🚀 Performance and Reliability

Error Handling

public static string GenerateSecurePassword(int length = 12)
{
    if (length < 12)
        throw new ArgumentException("La longitud mínima debe ser 12 caracteres");

    const int maxAttempts = 1000;
    int attempts = 0;

    while (attempts < maxAttempts)
    {
        string password = CreateRandomPassword(length);

        if (IsPasswordSecure(password))
            return password;

        attempts++;
    }

    throw new InvalidOperationException("No se pudo generar una contraseña segura");
}

This ensures the application never returns a weak password, even under unusual circumstances.

Memory Management

  • Secure disposal: RandomNumberGenerator is properly disposed
  • String handling: Minimal string operations to reduce memory footprint
  • No password storage: Generated passwords aren’t stored in memory longer than necessary

📈 Real-World Impact: Why This Matters

The Numbers Don’t Lie:

  • 81% of data breaches involve weak or stolen passwords
  • 59% of people use the same password everywhere
  • Common passwords can be cracked in seconds

This Tool’s Advantage:

  • Entropy: ~6.5 bits per character (vs ~4.7 for typical passwords)
  • Pattern resistance: Blocks 50+ common attack patterns
  • Educational: Users learn about password security through feedback

🛠 Getting Started

Installation

# Clone the repository
git clone https://github.com/brodznodev/password-generator-net.git
cd password-generator-net

# Build and run
dotnet build
dotnet run

Programmatic Usage

using SecurePasswordGenerator;

// Generate a 16-character secure password
string password = PasswordGenerator.GenerateSecurePassword(16);

// Validate an existing password
var strength = PasswordValidator.ValidatePassword("yourPassword123!");
Console.WriteLine($"Score: {strength.Score}/100");

🔮 Future Enhancements

I’m considering several improvements:

  1. Passphrase Generator: XKCD-style memorable passphrases
  2. Entropy Visualization: Show visual entropy distribution
  3. API Endpoint: RESTful API for integration
  4. Mobile App: Cross-platform mobile version
  5. Browser Extension: Direct integration with web forms
  6. Advanced Patterns: Machine learning-based pattern detection

🤝 Contributing

This is an open-source project under MIT license. I welcome contributions:

  • Bug reports: Found an issue? Let me know!
  • Feature requests: Have ideas? Open an issue
  • Code contributions: Pull requests welcome
  • Documentation: Help improve the docs
  • Testing: More test cases are always helpful

💭 Lessons Learned

Technical Insights:

  • Cryptographic APIs matter: The difference between Random and RandomNumberGenerator is security
  • User experience drives adoption: Good UX makes security tools actually useful
  • Comprehensive validation: It’s not enough to generate randomly—you must validate intelligently
  • Performance vs Security: Sometimes you need multiple attempts to generate truly secure passwords

Project Management:

  • Documentation is crucial: Good docs make or break open-source projects
  • Testing from day one: Security tools demand rigorous testing
  • Community feedback: Early feedback shaped major design decisions

🎯 Conclusion

Building a truly secure password generator taught me that security isn’t just about using the right algorithms—it’s about understanding the entire threat landscape and designing defenses accordingly.

This project goes beyond basic random generation to actively prevent common attack vectors while maintaining a user-friendly experience. The result is a tool that doesn’t just create passwords, but educates users about password security.

What’s next? I’m planning to add more features and would love your feedback. Have you tried the tool? What features would you like to see?

📚 References and Further Reading

What do you think? Have you built similar security tools? Share your experiences in the comments! 👇

GitHub Repository: github.com/brodznodev/password-generator-net

⭐ If you found this helpful, give the repo a star and let’s connect!


This content originally appeared on DEV Community and was authored by Bayron Rodezno