Generate truly random cryptographic keys using a random number generator in .NET

The well-known System.Random class lets us generate random numbers quickly. However, the values provided by System.Random are not truly random. Instead, they are pseudo-random. The return values should only be used in case true randomness is not that important, such as in the classic number-guessing game. In case you need a random value to be used in cryptography such as a cryptographic key in symmetric and asymmetric encryption then System.Random is not an acceptable option.

In addition System.Random is not thread-safe so it cannot be shared across multiple threads. The RNGCryptoServiceProvider class will generate random bytes in a fixed-length byte array. Cryptographic algorithms require keys of specific length such as 32-bit or 256-bit keys.

The following code shows an example of generating a random byte array and turning it into a readable base 64 string:

public string GenerateRandomCryptographicKey(int keyLength)
{
	RNGCryptoServiceProvider rngCryptoServiceProvider = new RNGCryptoServiceProvider();
	byte[] randomBytes = new byte[keyLength];
	rngCryptoServiceProvider.GetBytes(randomBytes);
	return Convert.ToBase64String(randomBytes);
}

If you call the above function with 32 as the keyLength parameter then you’ll get values similar to the following:

KRIJqfnv18xfqcBs1cuNj+zfs2RW5YWeJ42mxKy7fj4=
/zZem5fv7lLgu3oBs61fGH4f/krz9kZFEL5iTmmwGzs=

You can view the list of posts on Security and Cryptography here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Generate truly random cryptographic keys using a random number generator in .NET

  1. Carl Chan says:

    Nice example!

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.