views:

537

answers:

2

How can I use Membership.GeneratePassword to return a password that ONLY contains alpha or numeric characters? The default method will only guarantee a minimum and not a maximum number of non alphanumeric passwords.

I have the solution already but thought I'd share for future visitors.

.. Answer coming up.

+1  A: 
string newPassword = Membership.GeneratePassword(15, 0);
newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => "9" );

This regular expression will replace all non alphanumeric characters with the numeric character 9.

Curtis White
This will lose quite a bit of randomness in your password. Not recommended.
Matti Virkkunen
@Matti Possible to replace the "9" with Random.Next(0, 9) integer. Placing non alphanumeric characters into a typical password is typically overkill. A randomly generated password that doesn't use words is fine for many applications. The reason to do this is usability. Many non alpha-numeric characters are easily mistaken or confused or not able to be entered by average user.
Curtis White
@Matti It is also possible with this code to then go back and only insert a subset of approved non-alphanumeric characters. I don't see the need for any for many applications though.
Curtis White
@Curtis White: I prefer to draw the line where I consider a user fit to user a computer *above* the ability to read punctuation and use the keyboard correctly.
Matti Virkkunen
+1 Not sure why this was voted down. Whether or not you agree w/ the approach taken, this is a great answer to the question.
Kevin Babcock
And to comment on whether or not this is secure...using Random.Next() w/ the code above generates a password w/ 7.7e26 possible combinations - I'd say that is still very secure.
Kevin Babcock
+1  A: 

A simple way to get an 8 character alphanumeric password would be to generate a guid and use that as the basis:

string newPwd = Guid.NewGuid().ToString().Substring(0, 8);

If you need a longer password, just skip over the dash using substrings:

string newPwd = Guid.NewGuid().ToString().Substring(0, 11);
newPwd = newPwd.Substring(0, 8) + newPwd.Substring(9, 2); // to skip the dash.

If you want to make sure the first character is alpha, you could just replace it when needed with a fixed string if (newPwd[0] >= '0' && newPwd[0] <= '9')...

I hope someone can find this helpful. :-)

Laura Blood