terça-feira, 23 de outubro de 2012

Random number generation-RNGCryptoServiceProvider

Cryptographically secure pseudorandom number generator

 
    
A cryptographically secure pseudo-random number generator (CSPRNG) is a pseudo-random number generator (PRNG) with properties that make it suitable for use in cryptography.
Many aspects of cryptography require random numbers, for example:
The "quality" of the randomness required for these applications varies. For example creating a nonce in some protocols needs only uniqueness. On the other hand, generation of a master key requires a higher quality, such as more entropy. And in the case of one-time pads, the information-theoretic guarantee of perfect secrecy only holds if the key material is obtained from a true random source with high entropy.
Ideally, the generation of random numbers in CSPRNGs uses entropy obtained from a high quality source, which might be a hardware random number generator or perhaps unpredictable system processes — though unexpected correlations have been found in several such ostensibly independent processes. From an information theoretic point of view, the amount of randomness, the entropy that can be generated is equal to the entropy provided by the system. But sometimes, in practical situations, more random numbers are needed than there is entropy available. Also the processes to extract randomness from a running system are slow in actual practice. In such instances, a CSPRNG can sometimes be used. A CSPRNG can "stretch" the available entropy over more bits.

Source: http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator



Implementing the code using C#

using System;
using System.Security.Cryptography;
 

public class RNGCryptoServiceProviderHelper
{
    public static void Main()
    {
       using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
       {
           // Buffer storage.
           byte[] data = new byte[4];
           // Ten iterations.
          for (int i = 0; i < 10; i++)
           {
             // Fill buffer.
             rng.GetBytes(data);
             // Convert to int 32.
             int value = BitConverter.ToInt32(data, 0);
             Console.WriteLine(value);
           }
       }
    }

}

 

 
 
Postar um comentário