Baran Topal

Baran Topal


May 2024
M T W T F S S
« Feb    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories


random number generator vs. true random number generator and .NET

baranbaran

Say, I need a true random number generation between two positive integers (around 50000-60000).

In .NET, this is achievable by:


Random rnd = new Random();
int RandomNumber = rnd.Next(50000,60000);

Even if we flip a coin, the results are not actually random.  They are influenced by physical laws.

We have the option of influencing the order of numbers generated by seeding the random generator.
If we wish to have the sequence of numbers returned influenced by the time and date, we can try this:


int seed =  DateTime.Now.Ticks & 0x0000FFFF;
Random rnd = new Random(seed);
int RandomNumber = rnd.Next(50000,60000);

However, maybe we are unhpappy with a randomization that repeats frequently? When you place constraints on a random number generator you’re going to end up with a less random result. In an ideal situation each subsequent number has the exact same mathematical chance of coming up every time. That means in your number space you have a 1 in 10000 chance of a number appearing on any given try. You have the exact same chance, statistically, of getting the same number each time.

However, .NET does have a random number generator that is considered cryptographically secure.

https://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx


using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                    byte[] rngData = new byte[4];
                    rng.GetBytes(rngData);
                    int cryptoInt = BitConverter.ToInt32(rngData, 0);
                    int randomNumber = Math.Abs(cryptoInt) % 10000 + 50000;
            }