[英]C# : How to generate unique passwords with the length of 7 or 8 characters
我需要多次重复生成唯一密码,确保每次生成的密码都是唯一的,请帮帮我。
谢谢!
所以这是生成cryptedRandom密码和线程安全的另一种方法...
private string CryptedRandomString()
{
lock (this)
{
int rand = 0;
byte[] randomNumber = new byte[5];
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
Gen.GetBytes(randomNumber);
rand = Math.Abs(BitConverter.ToInt32(randomNumber, 0));
return ConvertIntToStr(rand);
}
}
private string ConvertIntToStr(int input)
{
lock (this)
{
string output = "";
while (input > 0)
{
int current = input % 10;
input /= 10;
if (current == 0)
current = 10;
output = (char)((char)'A' + (current - 1)) + output;
}
return output;
}
}
现在你可以像这样调用这个方法: -
string GeneratedPassword = "";
GeneratedPassword = CryptedRandomString() + CryptedRandomString();
Console.WriteLine(GeneratedPassword.Substring(0,8));
现在你们都必须想知道为什么GeneratedPassword = CryptedRandomString() + CryptedRandomString();
,我之前两次调用CryptedRamdomString()方法的原因只是为了确保它返回10个以上的数字,因为它更容易获得8个字符密码,否则如果它被调用一次,那么有时它会产生少于8个字符的密码。
那么在使用这种使用“RNGCryptoServiceProvider”生成随机数的方法之前你必须考虑一件事,比Random.Next有点耗时。 但是“RNGCryptoServiceProvider”比“Random.Next”更安全。
我为密码字母表定义了一组可能的字符,然后在该数组中生成7或8个随机索引以创建密码。
如果你想保证每个字符类型的最小数量等,这将需要改进。
你说全球独特的字符串?
System.Guid.NewGuid().ToString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.