This is a dumping ground of software development topics that I've run across and found interesting (mainly .NET development). Many topics are covered more thoroughly in other places, and much of the information is gleaned from other places, and I'll try to credit those sources when possible.

Thursday, February 01, 2007

Random Password Generator

I needed to create a random password. First I found this short method, which didn't work. Then I found this guy agreed with me. His code works, but not so hot in my test program. The parameterless Random constructor uses a time-based seed value (per millisecond?) so there are duplicates. The code I ended up with reuses a single Random member.

Then there's the holy grail, which was too much for the requirements I was working with, eight alphanumeric digits only. Simplicity is divine.

private Random m_random = new Random();

public string CreateRandomPassword(int length)
char[] chars = new char[length];

int index = 0;
while (index < length)
char c = (char)m_random.Next(48, 122);
if (Char.IsLetterOrDigit(c))
chars[index] = c;

return new string(chars);

No comments: