The implementation of RNGCryptoServiceProvider can generate cryptographically strong sequence of random values. Using this class, we can generate arbitrary length of random string. These strings can be used as unique keys if the length is long.
Here is the function:
public static string GenerateUniqueKey(int length)
{
const string AvailableCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
char[] key = new char[length];
byte[] randomData = new byte[length];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(randomData);
}
for (int i = 0; i < key.Length; i++)
{
int pos = randomData[i] % AvailableCharacters.Length;
key[i] = AvailableCharacters[pos];
}
return new string(key);
}
Here is the function:
public static string GenerateUniqueKey(int length)
{
const string AvailableCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
char[] key = new char[length];
byte[] randomData = new byte[length];
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(randomData);
}
for (int i = 0; i < key.Length; i++)
{
int pos = randomData[i] % AvailableCharacters.Length;
key[i] = AvailableCharacters[pos];
}
return new string(key);
}
Comments