c#隨機生成強密碼 至少包含一位數字、一位大寫字母和一位小寫字母
string chars = "0123456789ABCDEFGHIJKLMNOPQSTUVWXYZabcdefghijklmnpqrstuvwxyz";
Random randrom = new Random(getNewSeed());
string str = "";
for (int j = 0; j < 50; j++)
{
str = "";
for (int i = 0; i < 8; i++)
{
str += chars[randrom.Next(chars.Length)];//randrom.Next(int i)返回一個小於所指定最大值的非負隨機數
}
//不符合正則,重新生成
if (!Regex.IsMatch(str, @"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$"))
{
continue;
}
else {
break;
}
}
private static int getNewSeed()
{
byte[] rndBytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(rndBytes);
return BitConverter.ToInt32(rndBytes, 0);
}