Monday, July 6, 2015

Generate Random numbers using RNGCryptoServiceProvider in C#

Random numbers used for creating encryption keys and for hashing. Good random numbers are important in Cryptography as it deals with security. The .NET Framework has two ways to generating random values.
  1. System.Random 
  2. System.Security.Cryptography.RNGCryptoServiceProvider
System.Random:
System.Random is not good enough for cryptographic purposes. Microsoft recommends creating one instance of System.Random to generate numbers for your application. Check the link System.Random Class. Also it's not thread safe.

System.Security.Cryptography.RNGCryptoServiceProvider:
The RNGCryptoServiceProvider is used as cryptographic random number generators as it can not be predict. It is a more secure way to generate random numbers.
The following Console application sample generates 10 random values.
using System;
using System.Security.Cryptography;
static void Main()
{
    for (var i = 0; i < 10; i++)
    {
        int keySize = 32;
        var randomValueByte = GenerateRandomValue(keySize);
        Console.WriteLine(Convert.ToBase64String(randomValueByte));
    }

    Console.ReadLine();
}

public static byte[] GenerateRandomValue(int keySize )
{
    var randomValue = new byte[keySize];
    using (var randomValueGenerator = new RNGCryptoServiceProvider())
    {
        randomValueGenerator.GetBytes(randomValue);
    }
    return randomValue;
}
Output:
Check my another article to learn Cryptographic Hashing Algorithm in .Net.