While looking for best attempts at generating truly random numbers, I stumbled upon this code example.
Looking for opinions on this snippet.
<
I really do not suggest using provided example. Although RNGCryptoServiceProvider returns truly good random (or at least it should), but the same is not true for Random. Moreover - it is not known if Random(value) creates true bijection against value returned by Next(...). Moreover - it is not guaranteed that Next(min, max) returns the value in a truly random manner (meaning equal chances for number to hit each value).
I would first tear down the problem to getting a number in the interval 0 - max (exclusive). Then, I would use nearest power of 2 to get a random value in the range 0 - (2^n - 1). Now, one thing you MUST never do here is use modulo to get a number in the preferred range, like rand(0 - (2^n - 1)) % max, because by doing, so you are actually increasing chances of getting number in lower range.
Example: max = 3, n = 2 (0 - (2^2 - 1)) % 2, numbers (0, 1, 2, 3), corresponding values after modulo (0, 1, 2, 0). See that we hit 0 twice, which is really bad randomness.
So, the solution would be to use crypto random to get a value to nearest power of two, and in case the value is outside maximum range, repeat procedure (get another crypto random) until the value is inside the given range. This would be a much better algorithm.