Generate truly random cryptographic keys using a random number generator in .NET
December 18, 2016 1 Comment
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.
RNGCryptoServiceProvider is not thread safe and should be specified as a static readonly field.