RNGCryptoServiceProvider - Random Number Review

后端 未结 7 821
旧时难觅i
旧时难觅i 2020-12-05 17:48

While looking for best attempts at generating truly random numbers, I stumbled upon this code example.

Looking for opinions on this snippet.

<
7条回答
  •  攒了一身酷
    2020-12-05 18:32

    Well, using RNGCryptoServiceProvider gives you an unguessable crypto-strength seed whereas Environment.TickCount is, in theory, predictable.

    Another crucial difference would be evident when calling your NextInt method several times in quick succession. Using RNGCryptoServiceProvider will seed the Random object with a different crypto-strength number each time, meaning that it will go on to return a different random number for each call. Using TickCount risks seeding the Random object with the same number each time (if the method is called several times during the same "tick"), meaning that it will go on to return the same (supposedly random) number for each call.

    If you genuinely need truly random numbers then you shouldn't be using a computer to generate them at all: you should be measuring radioactive decay or something similarly, genuinely unpredictable.

提交回复
热议问题