C# – Random Password Generator – Video
I know a lot of people, having problems creating passwords. With the current code I will show you how to create a password using C#. The password consists of at least two capital letters, two small letters, a digit and three special characters. Furthermore, up to seven more chars are added, thus making its lenght a random between 8 and 15. Thus it is probably one of the best passwords ever, except for the fact it will be quite difficult for you to remember it.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class RandomPWDGerenrator
{
private const string CapitalLetters = "QWERTYUIOPASDFGHJKLZXCVBNM";
private const string SmallLetters = "qwertyuiopasdfghjklzxcvbnm";
private const string Digits = "0123456789";
private const string SpecialCharacters = "!@#$%^&*()-_=+<,>.";
private const string AllChars = CapitalLetters+SmallLetters+Digits+SpecialCharacters;
private static Random rnd = new Random();
static void Main()
{
StringBuilder password = new StringBuilder();
for (int i = 1; i <= 2; i++)
{
char capitalLeter = GenerateChar(CapitalLetters);
InsertAtRandomPositons(password,capitalLeter);
}
for (int i = 1; i <= 2; i++)
{
char smallLetter = GenerateChar(SmallLetters);
InsertAtRandomPositons(password,smallLetter);
}
char digit = GenerateChar(Digits);
InsertAtRandomPositons(password, digit);
for (int i = 1; i <= 3; i++)
{
char specialChar = GenerateChar(SpecialCharacters);
InsertAtRandomPositons(password,specialChar);
}
int count = rnd.Next(8);
for (int i = 1; i <= count; i++)
{
char specialChar = GenerateChar(AllChars);
InsertAtRandomPositons(password,specialChar);
}
Console.WriteLine("Your New Password is:");
Console.WriteLine(password);
Console.WriteLine("Your password consists of {0} elements.",password.Length);
Console.WriteLine();
Console.WriteLine();
}
private static void InsertAtRandomPositons(StringBuilder password, char character)
{
int randomPosition = rnd.Next(password.Length+1);
password.Insert(randomPosition,character);
}
private static char GenerateChar (string availableChars)
{
int randomIndex = rnd.Next(availableChars.Length);
char randomChar = availableChars[randomIndex];
return randomChar;
}
}
What is interesting in this code:
1. We have the variable “rnd” defined in the class, and not in the Main method, thus making it available for the whole class.
2. The Method GenerateChar() returns a random symbol. The method chooses a random position in a variety of symbols and returns the symbol of this position.
3. The method InsertAtRandomPosition() chooces a random position in the StringBuilder object and puts at this position a symbol.
Here is the video:
Disclaimer: The code is partially taken from the TelerikAcademy courses for programming & the free Bulgarian C# programming book.
You may find the exe file of this application here.