Previously we discussed about some of the smallest yet important topics in C# and .NET like where to use “Var” keyword, what is the importance of it. Also the meaning of GetType, TypeOf, Is keywords and their uses.

Now in this part of discussion we will discuss yet another interesting topic which is encountered by a C#, .NET developer. We will discuss about Random numbers and how & where they are used. How can we write a code for generating random numbers in C#.

Random Numbers:

First of all we understand what do we mean by random. So to understand the actual meaning of random, we say that something which is odd, unusual or unexpected is called as Random.

In a similar way we can apply this meaning in our programming concepts also. We can say that Random numbers are a set of unexpected numbers or we can say that something which we cannot predict.

Now basically if we want to generate a random number using C# then we can simply create a Random object as there is already a namespace of random provided. So create a random object and generate a random, but this is the basic method. The basic code is written below,

{

Random obj = new Random();

Console.WriteLine(obj.Next());

}

But now to really generate a random number we have to think a bit deeper or we have to put our thought process in knowing how the random number is generated and what the process behind it is.

For example if we ask a person to choose any number between 1 to 10, he can choose any number like 7 or 3 or 8 any number. Here we don’t know what number that person will choose the next time. This behavior we call it as randomness. Now we will see how this randomness phenomenon will work.

Now technically understanding the above example we can say that the process of randomness is not at all random but it is well thought process, in short we can say that the process is not as random as we think. Now the question comes to our mind that what triggers this randomness. So again taking the above example, observing we come to know that when we ask the person to choose any number from 1 to 10, the thought process which is in his mind letting him make the decision for which number to choose triggers the randomness. Like we can say that if the person’s favorite number is 7 he will select 7 or if he wants to achieve something big in his life and he always likes the big figures he will select number 10.

So this process is not that much random because I can easily guess what the person might be thinking or what is his thought process and according to that which number he will select. Because there is an initial thought or an initial trigger which forces the person to choose the number. This initial thought which triggers the randomness is called as “seed”. Therefore if we know the seed then we can predict the randomness, like if we know that the person likes big figures then we are sure that he will select 10 because we know the initial thought or the seed of that person.

In short we can conclude that if we know the seed we can predict the randomness and if we do not want anyone to predict the randomness then make sure that the seed is not known or unpredictable.

Classification:

Now based on the behavior of the randomness we can categorize it into two types:

  • Pseudo Random, whose seed is predictable
  • Secure Random, whose seed is unpredictable

Pseudo Random:

In Pseudo Random we can say that here we can predict the seed or the initial thought and therefore we can predict the randomness. In the above example of the random number generation code,

{

Random obj = new Random();

Console.WriteLine(obj.Next());

}

We can say that here the random number is generated using the CPU clock. Because we can predict the seed that is the CPU clock, we can predict the random number accordingly.

For business applications we can say that the Pseudo Random is used for Test Data. We do not want any kind of security while testing the application.

We write a code for understanding the Pseudo Random.

Class program

{

     Static Random obj = new Random();   // here the seeding happens

     Static void Main(string[] args)

        {

Console.WriteLine(GetPseudoRandom());

Console.WriteLine(GetPseudoRandom());

        }

      Private static string GetPseudoRandom()

         {

               Return obj.Next().Tostring();

         }

}

As we know that the random number is generated from CPU clock, if we declare Random object again and again we will get random numbers repeated because unless and until the CPU clock does not change we will get repeated random values. Therefore we have to declare the Random object only once. Here by default the seed is generated using CPU clock.

Now the question comes is it possible to override the by default seed because CPU clock is too much predictable. The answer is yes it is possible to override the seed with our own seed. To do this we have to create the Random object again and again because we will be providing the seed. The code below will make us understand easily,

Class program

{

     Static void Main(string[] args)

        {

Console.WriteLine(GetPseudoRandom(10));

Console.WriteLine(GetPseudoRandom(50));

        }

      Private static string GetPseudoRandom(int seed)

         {

               Random obj = new Random(seed);

               Return obj.Next().Tostring();

         }

}

So if we want to generate a random number for test data or any other purpose where we do not want to concern about security we use Pseudo Random as we can predict the seed and also override the seed in this type.

Secure Random:

Now what if we want to generate a random number which should not be easy to predict, we use Secure Random. As the name says Secure Random which means that we are not able to predict the seed due to which we are not able predict the randomness. The Secure Random is used in Cryptography or if we are creating a card game where we really want the predictability of the cards to be difficult.

Now we knew that the pseudo random number is generated using the seed which is CPU clock. But if we want to generate Secure Random number its seed should unpredictable. Now this seed is generated by the noise of our computer, mouse clicks, number of keys typed on the keyboard, thermal temperature of computer. These things produce a seed which is nearly impossible for a human to predict because it is difficult to think about these things.

Now to generate a secure random number in .NET we will create a new class and then use “RNGCryptoServiceProvider”. It comes under the namespace of system.security.cryptography. And why we use this cryptography namespace because we want to generate secure random number. We see a sample code to understand this,

Class program

{

     Static void Main(string[] args)

        {

Console.WriteLine(GetSecureRandom());

Console.WriteLine(GetSecureRandom());

         }

         Public static string GetSecureRandom()

          {

              Using (RNGCryptoServiceProviderrng = new RNGCryptoServiceProvider())

                 {

byte[] randomNumber = new byte[1000000];

rng.GetBytes(randomNumber);

int value = BitConverter.Toint32(randomNumber, 0);

returnvalue.Tostring();

                 }

         }

Here in the output of this program we get secure random numbers which are very random.Now the question is how the seed for RNGCryptoServiceProvider is generated.

The answer to that is Operating System Entropy. The seed is generated using operating system entropy. Here entropy which in English means lack of order or predictability or degree of randomness in system. We have heard this word in chemistry. But here the meaning of the entropy is same i.e. randomness. Here the randomness or entropy provided by the operating system is used to generate seed for cryptography. Random events provided by operating system such as mouse click events, key press from keyboard events, thermal temperature event, noise of the computer, etc.

For example if we take mouse click events, we see the process of how the seed is generated.

csharp

Here in the above image we have considered the mouse event times and then what happens is that these mouse click event times, differences between these times are taken. After taking 3-4 differences it selects the lowest value and does the Log of that value. In this image the lowest value is 2 and its Log (2) is taken. In this way the seed is generated using the randomness in mouse click events, also this type of random and complex process is done for other events like key press event, noise event, thermal temperature event, etc.

So in short if the seed is generated according to the natural events like the above ones then it is very difficult or nearly impossible for a human to predict the random number.

In the Pseudo Random type the seed was generated through the CPU clock which is easy to predict but here in the Secure Random there is a very complex process of measuring the events like noise of computer, mouse click event and do all the calculations and all which makes it difficult to predict the seed.

Now from the performance point of view we can say that generating Pseudo Random numbers is faster than generating Secure Random numbers. Because the Pseudo Random numbers generate seed from the CPU clock whereas the Secure Random numbers have lot of calculation for generating the seed. Random class is faster than crypto because the seed calculation is simple.

Unique Numbers:

Now often many of us are getting confused between random numbers and unique numbers. We tend to define both of them as same but they are not. According to definition Random numbers are a set of numbers or set of things from which we have to choose unpredictably whereas unique numbers are only one of its kinds available for that particular instance and will not repeat for that particular instance.

Now to generate a unique number in .NET we use “Guid” class which refers to Global Unique Identity which is of 32 characters and is unique in time and space.

To understand this we have a simple sample code here,

Class program

{

     Static void Main(string[] args)

{

String str = Guid.NewGuid().ToString();

Console.WriteLine(str);

         }

The output of this will gives us a unique number which is shown below,

c1

The unique number is shown in red underline.

Here we see there are dashes present in the unique number so if we want to remove the dashes we have to just write the code as,

Class program

{

     Static void Main(string[] args)

        {

              String str = Guid.NewGuid().ToString(“N”);

Console.WriteLine(str);

         }

Here “N” means only number. So the output of this will be a unique number without dashes.

If we want our unique number in braces then the code will be,

Class program

{

     Static void Main(string[] args)

        {

              String str = Guid.NewGuid().ToString(“B”);

Console.WriteLine(str);

         }

Here “B” means braces or brackets. The output of this will be a unique number with braces.

c2

The unique number with braces is shown in red underline.

In short concluding the discussion we can say that if,

  • We want to generate a unique number use “Guid” class in .NET
  • We want to generate pseudo random number use random class in .NET
  • We want to generate a secure random number use RNGCryptoServiceProvider in .NET
Advertisements