Membership Generate Password alphanumeric only password?

33,780

Solution 1

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.

Solution 2

I realised that there may be ways of doing this. The GUID method is great, except it doesn't mix UPPER and lower case alphabets. In my case it produced lower-case only.

So I decided to use the Regex to remove the non-alphas then substring the results to the length that I needed.

string newPassword = Membership.GeneratePassword(50, 0); 

newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => ""); 

newPassword = newPassword.Substring(0, 10);

Solution 3

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. :-)

Solution 4

You could also try to generate passwords and concatenate the non alphanumeric characters until you reach the desired password length.

public string GeneratePassword(int length)
{
    var sb = new StringBuilder(length);

    while (sb.Length < length)
    {
        var tmp = System.Web.Security.Membership.GeneratePassword(length, 0);

        foreach(var c in tmp)
        {
            if(char.IsLetterOrDigit(c))
            {
                sb.Append(c);

                if (sb.Length == length)
                {
                    break;
                }
            }
        }
    }

    return sb.ToString();
}
Share:
33,780
Curtis White
Author by

Curtis White

Updated on April 18, 2020

Comments

  • Curtis White
    Curtis White about 4 years

    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.

  • Matti Virkkunen
    Matti Virkkunen about 14 years
    This will lose quite a bit of randomness in your password. Not recommended.
  • Curtis White
    Curtis White about 14 years
    @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
    Curtis White about 14 years
    @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.
  • Matti Virkkunen
    Matti Virkkunen about 14 years
    @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.
  • Kevin Babcock
    Kevin Babcock almost 14 years
    +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
    Kevin Babcock almost 14 years
    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.
  • Jeff Swensen
    Jeff Swensen about 13 years
    Effectively the same exact answer as Laura's, with a string format specified for no reason (has zero effect).
  • E.Z. Hart
    E.Z. Hart almost 12 years
    This is not a good idea. For one, you're reducing your set of possible characters to 16 (instead of 36); for another, guids aren't necessarily random, and depending on the method use to generate the guid the passwords you're creating might be easily predictable. I highly recommend Eric Lippert's series on how guids work for more info about this: blogs.msdn.com/b/ericlippert/archive/2012/04/24/…
  • Muhammad Amin
    Muhammad Amin almost 11 years
    Thanks i have used it in my project
  • jsumrall
    jsumrall over 10 years
    Use 10 as your maximum since the upper limit is exclusive on the Random.Next method. string newPassword = Membership.GeneratePassword(8, 0); Random rnd = new Random(); newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => rnd.Next(0,10).ToString() );
  • Chris
    Chris over 10 years
    Although unlikely, it is feasible that the initial password generated could contain less than 10 alphanumeric characters, which would then result in ArgumentOutOfRangeException() thrown by the Substring() method.
  • RealSollyM
    RealSollyM over 10 years
    I beg to differ @Chris. The 50 in Membership.GeneratePassword specifies the length of the password, not just the MaxLength.
  • Chris
    Chris over 10 years
    @SollyM yes it does. However there is nothing to stop all 50 characters being symbols (i.e. not alphanumeric). It's unlikely, but feasible. If more than 40 were symbols, you would get an exception thrown by the Substring() method in the third line.
  • RealSollyM
    RealSollyM over 10 years
    I get what you mean now. Which makes sense. But unlikely due to the next digit being 0. That reduces the occurrence of the non-AlphaNumerics. I am sure technically speaking this could result in an error, but I have been using this code for 9 months without a problem whatsoever.
  • Silence Peace
    Silence Peace almost 7 years
    @"[^0-9]" is better then @"[^a-zA-Z0-9]" beacuaes its added some non alphabetical characters
  • user2685937
    user2685937 over 5 years
    GeneratePassword may be less than ideal. They use non crypto Random sometimes for non alphanumeric characters. See referencesource.microsoft.com/#System.Web/Security/… So that would result in less distributed usage of non-alphanumeric characters in theory. Looks like someone did that analysis and that does appear to be a reduction in randomness in their current algo for non-alphanumeric chars in some cases see poshhelp.wordpress.com/2017/01/30/…
  • Kyle Goode
    Kyle Goode about 2 years
    There is the difference that Laura's had to explicitly remove the dashes whereas the format string provided here would let someone get a longer set of characters without removing the dashes manually afterward.