Generating random numbers for cryptography
Sometimes you need to generate random numbers for use with cryptography in encryption or signing. There are a couple of classes that can generate random numbers in .NET.
The Random
class generates cryptographically weak pseudo-random numbers. This is not good enough for cryptography. If the random numbers are not truly random, then they are predictable, and then a cracker can break your protection.
For cryptographically strong pseudo-random numbers, you must use a RandomNumberGenerator
-derived type, such as those created by calling the RandomNumberGenerator.Create
factory method either with a named algorithm or using its default implementation.
We will now create a method to generate a truly random byte array that can be used in algorithms like encryption for key and IV values:
- In the
Protector
class, add statements to define a method to get a random key or IV for use in encryption, as shown in the following code: ...