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

后端 未结 7 1644
攒了一身酷
攒了一身酷 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:17

    Your custom method has two problems:

    1. It uses a global instance of Random, but doesn't use locking. => Multi threaded access can corrupt its state. After which the output will suck even more than it already does.
    2. It uses a predictable 31 bit seed. This has two consequences:
      • You can't use it for anything security related where unguessability is important
      • The small seed (31 bits) can reduce the quality of your numbers. For example if you create multiple instances of Random at the same time(since system startup) they'll probably create the same sequence of random numbers.

    This means you cannot rely on the output of Random being unique, no matter how long it is.

    I recommend using a CSPRNG (RNGCryptoServiceProvider) even if you don't need security. Its performance is still acceptable for most uses, and I'd trust the quality of its random numbers over Random. If you you want uniqueness, I recommend getting numbers with around 128 bits.

    To generate random strings using RNGCryptoServiceProvider you can take a look at my answer to How can I generate random 8 character, alphanumeric strings in C#?.


    Nowadays GUIDs returned by Guid.NewGuid() are version 4 GUIDs. They are generated from a PRNG, so they have pretty similar properties to generating a random 122 bit number (the remaining 6 bits are fixed). Its entropy source has much higher quality than what Random uses, but it's not guaranteed to be cryptographically secure.

    But the generation algorithm can change at any time, so you can't rely on that. For example in the past the Windows GUID generation algorithm changed from v1 (based on MAC + timestamp) to v4 (random).

    0 讨论(0)
提交回复
热议问题