Guid.NewGuid() VS a random string generator from Random.Next()

后端 未结 7 1655
攒了一身酷
攒了一身酷 2021-02-01 17:51

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

7条回答
  •  佛祖请我去吃肉
    2021-02-01 18:13

    As written in other answers, my implementation had a few severe problems:

    • Thread safety: Random is not thread safe.
    • Predictability: the method couldn't be used for security critical identifiers like session tokens due to the nature of the Random class.
    • Collisions: Even though the method created 20 'random' numbers, the probability of a collision is not (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;
        }
    }
    

提交回复
热议问题