774
Below is a C# Random Password Generator program that allows users to create strong passwords with customizable options, such as the length of the password and the inclusion of special characters, numbers, and uppercase/lowercase letters.
Full Code
using System;
using System.Text;
class PasswordGenerator
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Random Password Generator!");
while (true)
{
Console.WriteLine("\nChoose an option:");
Console.WriteLine("1. Generate a Random Password");
Console.WriteLine("2. Exit");
Console.Write("Enter your choice: ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
GeneratePassword();
break;
case "2":
Console.WriteLine("Goodbye!");
return;
default:
Console.WriteLine("Invalid choice. Please try again.");
break;
}
}
}
static void GeneratePassword()
{
// Ask the user for the password length
Console.Write("Enter the desired password length (minimum 6): ");
if (!int.TryParse(Console.ReadLine(), out int length) || length < 6)
{
Console.WriteLine("Invalid input. Password length must be at least 6.");
return;
}
// Ask the user if they want specific character types in the password
Console.Write("Include uppercase letters? (y/n): ");
bool includeUppercase = Console.ReadLine().Trim().ToLower() == "y";
Console.Write("Include lowercase letters? (y/n): ");
bool includeLowercase = Console.ReadLine().Trim().ToLower() == "y";
Console.Write("Include numbers? (y/n): ");
bool includeNumbers = Console.ReadLine().Trim().ToLower() == "y";
Console.Write("Include special characters? (y/n): ");
bool includeSpecial = Console.ReadLine().Trim().ToLower() == "y";
// Generate the password
string password = GenerateRandomPassword(length, includeUppercase, includeLowercase, includeNumbers, includeSpecial);
if (string.IsNullOrEmpty(password))
{
Console.WriteLine("No character types were selected. Unable to generate a password.");
}
else
{
Console.WriteLine($"Generated Password: {password}");
}
}
static string GenerateRandomPassword(int length, bool includeUppercase, bool includeLowercase, bool includeNumbers, bool includeSpecial)
{
// Define character pools
string upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
string numbers = "0123456789";
string specialCharacters = "!@#$%^&*()-_=+[]{}|;:,.<>?";
// Build the character pool based on user preferences
StringBuilder characterPool = new StringBuilder();
if (includeUppercase) characterPool.Append(upperCaseLetters);
if (includeLowercase) characterPool.Append(lowerCaseLetters);
if (includeNumbers) characterPool.Append(numbers);
if (includeSpecial) characterPool.Append(specialCharacters);
// If no character types were selected, return an empty string
if (characterPool.Length == 0) return string.Empty;
// Generate the password
StringBuilder password = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++)
{
int index = random.Next(0, characterPool.Length);
password.Append(characterPool[index]);
}
return password.ToString();
}
}
Explanation
- Main Menu:
- Displays a menu for the user to choose between generating a password or exiting the program.
- Handles user input using a switch statement.
- Ensures the program keeps running until the user selects the “Exit” option.
Console.WriteLine("1. Generate a Random Password"); Console.WriteLine("2. Exit"); - Input Validation:
- Validates the password length entered by the user (minimum of 6 characters).
- Prompts the user to choose whether to include uppercase, lowercase, numbers, and special characters in the password.
Console.Write("Include uppercase letters? (y/n): "); bool includeUppercase = Console.ReadLine().Trim().ToLower() == "y"; - Password Generation:
- Builds a character pool based on the user’s choices. Each selected category (uppercase, lowercase, numbers, special characters) adds characters to the pool.
- If no character types are selected, the method returns an empty string, and the program informs the user.
if (includeUppercase) characterPool.Append(upperCaseLetters); if (includeLowercase) characterPool.Append(lowerCaseLetters); if (includeNumbers) characterPool.Append(numbers); if (includeSpecial) characterPool.Append(specialCharacters);
- Random Password Construction:
- Uses the Random class to select random characters from the built character pool.
- Appends these characters to a StringBuilder to construct the password.
for (int i = 0; i < length; i++) { int index = random.Next(0, characterPool.Length); password.Append(characterPool[index]); } - Output:
- Displays the generated password or an error message if no valid character pool was selected.
Console.WriteLine($"Generated Password: {password}");
Sample Run
Run the program:
Welcome to the Random Password Generator! Choose an option: 1. Generate a Random Password 2. Exit Enter your choice: 1 Enter the desired password length (minimum 6): 12 Include uppercase letters? (y/n): y Include lowercase letters? (y/n): y Include numbers? (y/n): y Include special characters? (y/n): n Generated Password: Aa1lZ9kR5tPq
Validation and Edge Cases
- Minimum Length:
- Ensures the password length is at least 6 characters. If not, the user is prompted to enter a valid length.
- No Character Types Selected:
- If the user doesn’t select any character types, the program cannot generate a password and informs the user.
- Randomness:
- The Random class ensures the generated password is sufficiently random.
Features
- Customizable Passwords:
- Users can specify password length and choose which character types to include.
- Validation:
- Ensures valid input for password length and character type selection.
- Strong Passwords:
- Generates strong passwords with combinations of uppercase, lowercase, numbers, and special characters.
- Reusable Method:
- The GenerateRandomPassword method can be reused in other programs.
Ideas for Enhancement
- Ensure Balanced Composition:
- Modify the program to ensure that at least one character from each selected type (e.g., uppercase, numbers) appears in the password.
- Add Clipboard Copying:
- Automatically copy the generated password to the clipboard.
- Save Passwords:
- Store the generated passwords in a secure file or password manager.
- GUI Version:
- Use Windows Forms or WPF to create a graphical user interface for the password generator.
