Skip to main content

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.

// Hashing messages using various hash algorithms in .NET

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

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

//
// Usage
//

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);