[英]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.