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

Cha*_*thz 2 c# security asp.net-mvc asp.net-membership

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

string Password = Membership.GeneratePassword(12, 1);
Run Code Online (Sandbox Code Playgroud)

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

密码必须至少有一位('0'-'9')。

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

Ian*_*Ian 5

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

如果你想避免作为数字改变的位置成为你作为较低字符改变的位置,只需存储rand.Next(Password.Length)在第一个数字代中,避免第二个具有相同的值。

或者,更可靠的是,我们可以在每次执行替换操作时定义一个ListofnonSelectedIndexes并从中挑选和删除一个随机数:

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 
Run Code Online (Sandbox Code Playgroud)

注意:如果您将其用于任何与安全相关的事情,请考虑 SilverlightFox 先生的 评论