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.

Advertisements

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

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: