I want to generate unique and secure strings randomly and I want to do it over time. I want to choose the shortest possible length for my use (Big enough so that random tries fail with good chance). I Also want the process to be fast. Using the following code and testing it for uniqueness, duplicates occur sooner than I expected. I'm not sure if there is any problem. P.S.: Is it secure to use a pool for generated numbers? P.P.S: I prefer not to add '-' and '_' to the alphabet. Is it worth removing it?
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
string Random(int length,string alphabet)
{
StringBuilder result = new StringBuilder();
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
for (int i = 0; i < lenght; i++)
{
byte[] buffer = new byte[sizeof(uint)];
rng.GetBytes(buffer);
uint num = BitConverter.ToUInt32(buffer, 0);
result.Append(alphabet[(int)(num % (uint)alphabet.Length)]);
}
}
return result.ToString();
}
Aucun commentaire:
Enregistrer un commentaire