开发者

Membership Generate Password alphanumeric only password?

How can I use Membership.GeneratePassword to return开发者_StackOverflow 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.


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.


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);


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


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();
}


There is similar approach with breigo's solution. Maybe this is not so effective but so clear and short

string GeneratePassword(int length)
{
     var password = "";
     while (password.Length < length)
     {
          password += string.Concat(Membership.GeneratePassword(1, 0).Where(char.IsLetterOrDigit));
     }
     return password;
}


I also prefer the GUID method - here's the short version:

string password = Guid.NewGuid().ToString("N").Substring(0, 8);


Going from @SollyM's answer, putting a while loop around it, to prevent the very unlikely event of all characters, or too many characters being special characters, and then substring throwing an exception.

private string GetAlphaNumericRandomString(int length)
{
    string randomString = "";
    while (randomString.Length < length)
    {
      //generates a random string, of twice the length specified, to counter the 
      //probability of the while loop having to run a second time
      randomString += Membership.GeneratePassword(length * 2, 0);

      //replace non alphanumeric characters
      randomString = Regex.Replace(randomString, @"[^a-zA-Z0-9]", m => "");
    }
    return randomString.Substring(0, length);
}


This is what I use:

public class RandomGenerator
{
    //Guid.NewGuid().ToString().Replace("-", "");
    //System.Web.Security.Membership.GeneratePassword(12, 0);

    private static string AllowChars_Numeric = "0123456789";
    private static string AllowChars_EasyUpper = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static string AllowChars_EasyLower = "0123456789abcdefghijklmnopqrstuvwxyz";
    private static string AllowChars_Upper_Lower = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static string AllowedChars_Difficult = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()";

    public enum Difficulty
    {
        NUMERIC = 1,
        EASY_LOWER = 2,
        EASY_UPPER = 3,
        UPPER_LOWER = 4, 
        DIFFICULT = 5
    }

    public static string GetRandomString(int length, Difficulty difficulty)
    {
        Random rng = new Random();
        string charBox = AllowedChars_Difficult;

        switch (difficulty)
        {
            case Difficulty.NUMERIC:
                charBox = AllowChars_Numeric;
                break;
            case Difficulty.EASY_LOWER:
                charBox = AllowChars_EasyUpper;
                break;
            case Difficulty.EASY_UPPER:
                charBox = AllowChars_EasyLower;
                break;
            case Difficulty.UPPER_LOWER:
                charBox = AllowChars_Upper_Lower;
                break;
            case Difficulty.DIFFICULT:
            default:
                charBox = AllowedChars_Difficult;
                break;
        }

        char[] chars = new char[length];

        for (int i=0; i< length; i++)
        {
            chars[i] = charBox[rng.Next(0, charBox.Length)];
        }

        return new string(chars);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜