Hashing messages using various hash algorithms in .NET

A hash of a message can be viewed as its unique identifier. A series of bytes, such as a string, can be converted into hash, also called a message digest. A message digest is also a byte array that can be converted into a base 64 string for better readability. There are various hashing algorithms out there that can calculate the hash of a message. Ideally each algorithm should produce a different digest for each message, i.e. “Hello world” should yield a different hash from what “H3llo world” produces. I.e. a single change in the byte sequence will change the resulting hash. Also, it should be impossible to calculate the original message from a hash. Therefore hashing is a one-way cryptographic operation.

Why do we hash messages? The main purpose of hashing is integrity. If I send a message to another person then I can also send the hash of the message. The recipient can calculate the hash of the message and if their value is different from what I sent them then they’ll know that the message has been corrupted. Another important application of hashing is storing passwords. Normally we don’t store passwords in plain text but only some kind of hashed version.

The most frequently used algorithms out there are MD5 and the various SHA – Secure Hash – algorithms: SHA-1, SHA-2 and https://en.wikipedia.org/wiki/SHA-3. MD5 and SHA-1 are now considered outdated due to some flaws in their design. In modern applications we should use SHA-2 or SHA-3. Currently there’s no built-in support for SHA-3 in .NET.

These algorithms vary in the size of the digest they produce:

  • MD5: 128-bit
  • SHA-1: 160-bit
  • SHA-2: comes in various sizes: SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256 of which SHA-256 and SHA-512 are the most commonly used

It’s easy to calculate the hashes of various messages in .NET. The hash algorithms all derive from the HashAlgorithm abstract base class. The concrete implementations can be used in an identical way. This makes it easy for the caller to specify the actual hashing algorithm.

Here’s a generic function that calculates the hash of a message and returns a human readable message digest:

using System;
using System.Security.Cryptography;
using System.Text;

namespace HashingAlgos
{
	public class Hasher
    {
		public string CalculateMessageDigest(string originalMessage, HashAlgorithm hashAlgo)
		{
			return Convert.ToBase64String(hashAlgo.ComputeHash(Encoding.UTF8.GetBytes(originalMessage)));
		}
    }
}

The following example shows the usage for MD5, SHA-1, SHA-256 and SHA-512:

using System.Security.Cryptography;

Hasher hasher = new Hasher();
string originalMessage = "Hello world";
string messageDigestMd5 = hasher.CalculateMessageDigest(originalMessage, MD5.Create());
string messageDigestSha1 = hasher.CalculateMessageDigest(originalMessage, SHA1.Create());
string messageDigestSha256 = hasher.CalculateMessageDigest(originalMessage, SHA256.Create());
string messageDigestSha512 = hasher.CalculateMessageDigest(originalMessage, SHA512.Create());

Console.WriteLine(messageDigestMd5);
Console.WriteLine(messageDigestSha1);
Console.WriteLine(messageDigestSha256);
Console.WriteLine(messageDigestSha512);

Here are the hashes from top to bottom:

PiWWCnnbxptnTNTsZ6csYg==
e1AsOh9IyGCa4hLN+2Od7jlnP14=
ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=
t/eDuu2Cl/DbkXRiGE/08I5pwtXl95qUJgD5cl9Yzh8pwYE5v4CwbA//K900c4RS7PQMSIwip+PYDN9vnBwNRw==

Note how the hash size increases for the same message. If we change a single byte, like “H3llo world” then we get completely different values:

4nk9VtzkZxu53YWw4oa7Tg==
A3wblKv3U/N9q7F+eYbwjPiJet8=
VZ/219WyfgHrSNTpOJLXpSQwTzzaDboxYM3FQhMOF6g=
Y19sinP/GhBBsK2eq8hEvnfnX0CBzhxbiYB15pbo4hJEjpq/zKG3kEQXoG23uhXPuYilfg6VWhhwuZlPp4QiOA==

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

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Ricos Blog zu Softwaredesign- und architektur

Ideen und Gedanken rund um Softwaredesign und -architektur, Domain-Driven Design, C# und Windows Azure

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: