My colleague and I are debating which of these methods to use for auto generating user ID\'s and post ID\'s for identification in the database:
One option uses a single
As written in other answers, my implementation had a few severe problems:
(number of possible chars)^20
due to the seed value only being 31 bits, and coming from a bad source. Given the same seed, any length of sequence will be the same.Guid.NewGuid()
would be fine, except we don't want to use ugly GUIDs in urls and .NETs NewGuid() algorithm is not known to be cryptographically secure for use in session tokens - it might give predictable results if a little information is known.
Here is the code we're using now, it is secure, flexible and as far as I know it's very unlikely to create collisions if given enough length and character choice:
class RandomStringGenerator
{
RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
public string GetRandomString(int length, params char[] chars)
{
string s = "";
for (int i = 0; i < length; i++)
{
byte[] intBytes = new byte[4];
rand.GetBytes(intBytes);
uint randomInt = BitConverter.ToUInt32(intBytes, 0);
s += chars[randomInt % chars.Length];
}
return s;
}
}