包含一个数字以自动生成密码

Include a digit to automatically generate password

我正在使用以下代码片段自动生成密码

string Password = Membership.GeneratePassword(12, 1);

但这里有时它生成的密码没有数字值然后我得到以下错误

Passwords must have at least one digit ('0'-'9').

如何升级以上代码以生成数字值

public static Random numGenerator = new Random();

...

string Password = Membership.GeneratePassword(12, 1);

if(!Regex.IsMatch(Password, "\d"))
   Password += numGenerator.GetNext(0, 10);

您可以进一步处理生成的密码,如果它不包含数字,您将其中一个随机更改为这样的数字:

if (!Password.Any(x => char.IsDigit(x))){
    Random rand = new Random();
    char[] pass = Password.ToCharArray();
    pass[rand.Next(Password.Length)] = Convert.ToChar(rand.Next(10) + '0');
    Password = new string(pass);
}

如果你想避免没有小字符,你可以添加另一个检查,例如:

if (!Password.Any(x => char.IsLower(x))) {
    //Do similarly but using rand.Next(26) + 'a' instead of rand.Next(10) + '0'
}

并且如果你想避免已经改变为数字的位置成为你改变为小写字符的位置,只需将 rand.Next(Password.Length) 存储在第一代数字中并避免具有相同的值第二。

或者,更稳健地,我们可以定义一个 nonSelectedIndexesList 和 pick-and-remove 每次我们执行替换操作时从中定义一个随机数:

List<int> nonSelectedIndexes = new List<int>(Enumerable.Range(0, Password.Length));
Random rand = new Random();

if (!Password.Any(x => char.IsDigit(x))) { //does not contain digit
    char[] pass = Password.ToCharArray();
    int pos = nonSelectedIndexes[rand.Next(nonSelectedIndexes.Count)];
    nonSelectedIndexes.Remove(pos);
    pass[pos] = Convert.ToChar(rand.Next(10) + '0');
    Password = new string(pass);
}

if (!Password.Any(x => char.IsLower(x))) { //does not contain lower
    char[] pass = Password.ToCharArray();
    int pos = nonSelectedIndexes[rand.Next(nonSelectedIndexes.Count)];
    nonSelectedIndexes.Remove(pos);
    pass[pos] = Convert.ToChar(rand.Next(26) + 'a');
    Password = new string(pass);
}

if (!Password.Any(x => char.IsUpper(x))) { //does not contain upper
    char[] pass = Password.ToCharArray();
    int pos = nonSelectedIndexes[rand.Next(nonSelectedIndexes.Count)];
    nonSelectedIndexes.Remove(pos);
    pass[pos] = Convert.ToChar(rand.Next(26) + 'A');
    Password = new string(pass);
}

//And so on
//Do likewise to any other condition 

注意:如果您将其用于任何用途,请consider Mr. SilverlightFox security-related。

我有一个简单的方法:

string Password = Membership.GeneratePassword(12, 1);
Password = Password + "1"

如果您在生成临时密码时提示您的用户在登录时更改密码,这将很有帮助。