Function for Creating Passwords

Published 05 October 04 07:37 PM | mhawley

One of the things most of us have to do at one point or another, is generate a random password. I once thought this was a daunting task, however found some code at some point or another that gave me great headway into creating a good password generator.

 

private static string CreatePassword(int lengthOfPassword)
{
string[] characters = new string[32] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "2", "3", "4", "5", "6", "7", "8", "9"}; string password = "";
Random rnd = new Random();
while(password.Length < lengthofpassword)
{
// choose a random character from the array and add it to the password
password +="" characters[rnd.next(36)];
}

// return the generated password
return password;
}

Now, this won't create the best darn password out there, but its a great quick & dirty way of creating a dynamic password for your website.
Filed under:

Comments

# anon said on October 5, 2004 11:21 PM:

it's a good idea to drop the l and 1 & 0 and 0 characters as depending on the font, they can be very hard to distinguish between.

# Richard Tallent said on October 5, 2004 11:25 PM:

Latgely, I've taken to doing this using GUIDs:

Dim pass As Guid.NewGuid.ToString("n").Substring(0,6)

Works great...

# Matt Hawley said on October 5, 2004 11:29 PM:

Thanks anon, duly noted and removed from my code. I got charachter happy. Richard, thats a good idea too, however you wouldn't be able to create a password of 20 chars, or in my case 8 from the GUID.

# Wes said on October 5, 2004 11:52 PM:

Why did you create an array of strings? You can do the same thing with a single string.

string characters = "abcde....

Just curious.

# Matt Hawley said on October 5, 2004 11:58 PM:

No particular reason, like I said I pulled this code a long time ago and I needed it again for a new project. Works great either way.

# Matt said on October 6, 2004 12:18 AM:

It won't work if complexity requirements are enforced on the system the passwords are generated for.

# Matt Hawley said on October 6, 2004 12:23 AM:

Never said it would, just a quick & dirty way of generating a random password for websites and what not. This shouldn't be used to create network / domain passwords.

# TrackBack said on October 6, 2004 01:37 AM:
# TrackBack said on October 6, 2004 01:56 AM:
# Michael Teper said on October 6, 2004 05:43 AM:

A small perf suggestion -- init the string (or array, whatever works for you) as a private static member outside the function.

# Gareth said on October 9, 2004 07:29 PM:

Here another nice class for your collection

http://weblogs.asp.net/garethbrown/archive/2004/04/02/106216.aspx

This Blog

News

.NET Links

Blogs I Read

Syndication