我正在制作一个可以生成密码的密码生成器。
var listOfCharacters = "abcdefghijklmnopqrstuvwxyz" //the chars which are using
chars = listOfCharacters.ToCharArray();
string password = string.Empty;
for (int i = 0; i < length; i++)
{
int x = random.Next(0, chars.Length); //with random he is picking a random char from my list from position 0 - 26 (a - z)
password += chars.GetValue(x); // putting x (the char which is picked) in the new generated password
}
if (length < password.Length) password = password.Substring(0, length); // if the password contains the correct length he will be returns
return password;
我的随机:
random = new Random((int)DateTime.Now.Ticks);
我正在寻找一种比使用 Ticks 更快的方法来生成密码,因为它对我来说不够快。我正在寻找一个简单的代码,我可以轻松地将其放入上面的代码中。我只是 C# 的初学者。这样我仍然可以使用 int x = random.Next(0, chars.Length);
,但不是Random.next
更快。
编辑:当我想要两个在短时间内生成两个密码时。Ticks 会变慢
我的测试代码:
[TestMethod]
public void PasswordGeneratorShouldRenderUniqueNextPassword()
{
// Create an instance, and generate two passwords
var generator = new PasswordGenerator();
var firstPassword = generator.Generate(8); //8 is the length of the password
var secondPassword = generator.Generate(8);
// Verify that both passwords are unique
Assert.AreNotEqual(firstPassword, secondPassword);
}