Friday, May 18, 2007

Password Generator

You have probably got in situations when you need a password generator, somethimes for generating keys like for generating ticket for thin client using webservices, or for your personal use when you need to create a key for user account, but want that to be randomly. Here is a good piece of code for generating simple or strong passwords.

public static string GeneratePassword(int passwordLen, bool includeSmallLetters, bool includeBigLetters,
                            bool includeNumbers, bool includeSpecialCharacters)
{
   char[] returnValue = new char[passwordLen];
   char[] Choises;
   string smallLetters = string.Empty;
   string bigLetters = string.Empty;
   string numbers = string.Empty;
   string specialcharacters = string.Empty;

   int choisesLen = 0;

   if (includeSmallLetters)
   {
      smallLetters = "abcdefghijklmnopqrstuvwxyz";
      choisesLen += smallLetters.Length;
   }
   if (includeBigLetters)
   {
      bigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      choisesLen += bigLetters.Length;
   }
   if (includeNumbers)
   {
      numbers = "012345678901234567890123456789";
      choisesLen += numbers.Length;
   }
   if (includeSpecialCharacters)
   {
      specialcharacters = "~`!@#$%^&*()-_+=\|<,>.?/ {[}]";
      choisesLen += specialcharacters.Length;
   }
   if (choisesLen == 0)
      throw new ArgumentOutOfRangeException("includeSmallLetters",
                                  "At least one type of characters must be included!");

   Choises = (smallLetters + bigLetters + numbers + specialcharacters).ToCharArray();
   Random rnd = new Random();

   for (int i = 0; i < passwordLen; i++)
   {
      returnValue[i] = Choises[rnd.Next(choisesLen - 1)];
   }
   return new string(returnValue);
}

1 comment:

Sibusiso said...

I think this is the best way to genate keys because I was relying on the database to generate unique key an then retreive them, but now I can just do it in code, Thanks man :)