This is the 3rd part in a short series on cryptography in .NET. In the previous 2 articles I covered using Symmetric algorithms like AES and Asymmetric algorithms like RSA. In this section I want to cover random number generation and hashing. This will lead into the final article which will be about combining cryptographic primitives to create hybrid encryption protocols.

Cryptography in .NET : Random Numbers
Cryptography in .NET : Random Numbers

The primitive I want to discuss is generating cryptographically strong random numbers. This is useful if you want to generate random session keys for AES for example. To generate a random number you use the RNGCryptoServiceProvider class in .NET. Once you have constructed the object you just call GetBytes() and pass in the length in bytes of the random number you want to generate.

    public class RandomNumberGenerator
    {
        public byte[] Generate(int length)
        {
            using (RNGCryptoServiceProvider randomNumberGenerator = new RNGCryptoServiceProvider())
            {
                byte[] randomNumber = new byte[length];
                randomNumberGenerator.GetBytes(randomNumber);

                return randomNumber;
            }
        }
    }

The other option for generating random numbers is using the Random class which for a lot of purposes is fine, but the quality of pseudo random numbers is not as good as using RNGCryptoServiceProvider, making the latter better for cryptographic purposes, but you do pay a price for performance. As a quick test I created a loop that calls each implementation 10 times. RNGCryptoServiceProvider.GetBytes() took around 2800ms and Random.Next() took around 9ms.

Cryptographic Hashes are like Digital Finger Prints
Cryptographic Hashes are like Digital Finger Prints

The 2nd primitive I want to discuss is that of hashing and SHA-256 in particular. A cryptographic hash function is an algorithm that takes an arbitrary block of data and returns a fixed-size string, the (cryptographic) hash value, such that any (accidental or intentional) change to the data will change the hash value. The data to be encoded is often called the “message,” and the hash value is sometimes called the message digest or simply digest.

The ideal cryptographic hash function has four main properties:

    • It is easy to compute the hash value for any given message.
    • It is infeasible to generate a message that has a given hash.
    • It is infeasible to modify a message without changing the hash.
    • It is infeasible to find two different messages with the same hash.

Another way of thinking of a hash function is that of creating a unique fingerprint of a piece of data. Generating a hash digest of a block of data is very easy in .NET. There are various algorithms you can use like MD5, SHA1, SHA256, but for this article I will focus on SHA256 as that is probably the most common one used these days.

 Just like with the cryptographic random number generation, the code to hash some data is very straight forward.

    public class SecureHash
    {
        public byte[] ComputeHash(byte[] toBeHashed)
        {
            using (SHA256 sHA256 = SHA256Managed.Create())
            {
                return sHA256.ComputeHash(toBeHashed);
            }
        }
    }

The ComputeHash() method of the SHA256 class simply takes a byte array of your data to be hashed and then outputs another byte array with the hash (or unique finger print).

If you was to change even just a single bit of the data being passed into the ComputeHash() method then the calculated digest would be different.

A common use for a hash is to check the integrity of data being passed over a network. Before sending some data you calculate and send a hash. Then when the recipient receives the data you recalculate the hass on the received data and make sure it matched the original hash. If it doesn’t then the data was changed or corrupted on transit.

Hashes are also commonly used for storing passwords in databases. Instead of storing the actual text of a password you store a hash instead. Then any application that wants to authenticate a password just has to calculate the password has first and then compare it to that stored in the database.

That concludes this article on generating random numbers and calculating hashes. In the next instalment I shall discuss using these different cryptographic primitives to create what is known as a hybrid encryption algorithm.

Participate with Coding in the Trenches on Facebook
Participate with Coding in the Trenches on Facebook by Click the button above.
Advertisements

8 comments

  1. Cheers Steven 🙂 I knew the random generator was there, but I couldn’t find the docs, my previous code or the saved book marks I had, then your article popped up on the first page of my Google results…

    Shawty

  2. Glad it was useful 🙂 I explain a lot of this in more detail in my book for Syncfusion which should hopefully be out within the next 2 to 3 weeks.

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