C# Password Generator

  1. public static string GeneratePassword(int minLen, int maxLen, bool isUpperCase = true, bool isLowerCase = true, bool isNumber = true, bool isSymbol = true)
  2. {
  3.     string allowedChars = string.Empty;
  4.     if (isUpperCase)
  5.         allowedChars += "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
  6.     if (isLowerCase)
  7.         allowedChars += "abcdefghiklmnopqrstuvwxyz";
  8.     if (isNumber)
  9.         allowedChars += "1234567890";
  10.     if(isSymbol)
  11.         allowedChars += "!'^#+$%&/{([)]=}*?\\_-@~,;:<>";
  12.  
  13.     Random rd = new Random();
  14.     StringBuilder sb = new StringBuilder();    
  15.            
  16.     int len = rd.Next(minLen, maxLen);
  17.     int randomIndex;
  18.     char randomChar;
  19.     for (int i = 0; i <= len; i++)
  20.     {
  21.         randomIndex = rd.Next(allowedChars.Length);
  22.         randomChar = allowedChars[randomIndex];
  23.         sb.Append(randomChar);
  24.     }
  25.  
  26.     return sb.ToString();
  27. }

Here is the result for min length = 5 and max length = 15
rsN\&,Juk
~1-?Q'~Mku
wFnElGP:L+8sA
FN#'(i
Q6oid5l
xe$iFlD
ft*kA;
)u-)Kx
o3L2fn>9
o%=2i-


Random object use seed from system clock. If you are going to create passwords consecutive in very small time interval, probably random.next will return same value. In this case define random object as a static field. Also you can pass it as parameter. Even you can seed random object by yourself but you must change seed value everytime you call. You can use a counter.

  1.     Random rd = new Random(seed);
m ant / Mechanical Ant