Wednesday, June 11, 2008

Random Password Generation

I have previously written article on how to Generate Registration Image on Fly

Enhancing the same password generation logic so that it would be useful for generating random password using C# code.



public static string GetRandomPassword(int length)
{
char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
string password = string.Empty;
Random random = new Random();

for (int i = 0; i < length; i++)
{
int x = random.Next(1,chars.Length);
//Don't Allow Repetation of Characters
if (!password.Contains(chars.GetValue(x).ToString()))
password += chars.GetValue(x);
else
i--;
}
return password;
}

Its a simple logic instead by generating a random number between 1 and Length of characters. It also checks that same character is not repeated in generated password and finally return the randomly generated password string of desired length.

2 comments:

gaz said...

I like the idea, however if you request a length greater than the total amount of characters available does it end if the dreaded infinite loop? As you are saying, if character is already used -1 on the i. So if all are used we will always never reach the full length.

DotNetGuts said...

Yeep u r correct gaz, but it is already about 80+ chars and i don't think most of time we go for more than 20+ chars auto generated password as this will going to be change on first login. Another obvious solution is you can remove the if condition which don't allow repeatation of chars in password which can resolve your problem.

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape