我需要写一个密码生成器,它生成的密码至少有2个小写字母、2个大写字母、1个数字和1个特殊字符。它还必须是用户给定的长度。如何使用此代码为密码指定最小长度。例如:10?
这就是我一直在忍受的问题,但我试图限制长度,但没有成功,所以我只是删除了这些代码:
class Program
{
private const string Capital = "ABCDEFGHIJKLMNOUP";
private const string Lower = "abcdefghijklmnoup";
private const string Digit = "1234567890";
private const string Spec = "@&#><-[]Łł$ß";
private const string AllChars = Capital + Lower + Digit + Spec;
private static Random r = new Random();
static void Main(string[] args)
{
StringBuilder password = new StringBuilder();
for (int i = 1; i <= 2; i++)
{
char capitalLetter = GenerateChar(Capital);
InsertAtRandomPos(password, capitalLetter);
}
for (int i = 1; i <= 2; i++)
{
char lowerLetter = GenerateChar(Lower);
InsertAtRandomPos(password, lowerLetter);
}
for (int i = 1; i <= 3; i++)
{
char digit = GenerateChar(Digit);
InsertAtRandomPos(password, digit);
}
for (int i = 1; i <= 1; i++)
{
char specialLetter = GenerateChar(Spec);
InsertAtRandomPos(password, specialLetter);
}
Console.WriteLine("A jelszava: {0}",password);
Console.ReadKey();
}
private static void InsertAtRandomPos(StringBuilder password, char character)
{
int randomPosition = r.Next(password.Length + 1);
password.Insert(randomPosition, character);
}
private static char GenerateChar(string availableChars)
{
int randomIndex = r.Next(availableChars.Length);
char randomChar = availableChars[randomIndex];
return randomChar;
}
}
}
以下是一个可能对您有所帮助的代码片段:
static readonly Random r = new Random();
public static string GeneratePassword(
int length,
bool useLowercase,
bool useUppercase,
bool useDigits,
bool useSpecialChars,
string userDefined = null,
int[] skipCodes = null,
bool distinct = false
)
{
if (!useLowercase &&
!useUppercase &&
!useDigits &&
!useSpecialChars &&
userDefined is null)
return "";
var codes = new List<int>();
var ri = 0;
var code = 0;
while (codes.Count < length)
{
code = 0;
ri = r.Next(0, 5); //get a random option.
switch (ri)
{
case 0 when useLowercase:
code = r.Next(97, 123);
break;
case 1 when useDigits:
code = r.Next(48, 58);
break;
case 2 when useUppercase:
code = r.Next(65, 91);
break;
case 3 when useSpecialChars:
switch(r.Next(0, 4))
{
case 0:
code = r.Next(33, 48);
break;
case 1:
code = r.Next(58, 65);
break;
case 2:
code = r.Next(91, 96);
break;
case 3:
code = r.Next(123, 126);
break;
}
if (skipCodes != null && skipCodes.Contains(code))
code = 0;
break;
case 4 when userDefined != null:
code = Convert.ToChar(userDefined
.Substring(r.Next(0, userDefined.Length), 1));
break;
}
if ((distinct && codes.Contains(code)) || code == 0)
continue;
codes.Add(code);
}
return string.Join("", codes.Select(c => (char)c));
}
然后您可以生成如下密码:
var userDefined = "-#_$";
//The chars that you don't want to be included like white spaces commas..etc.
int[] skipCodes = new[] { 32, 39, 44, 96, 124 };
var pass = GeneratePassword(12, true, true, true, false, userDefined, skipCodes, true);
Console.WriteLine(pass);
或者多次调用它以生成特定的模式。调整它以满足您的需求。