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];
	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:


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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

%d bloggers like this: