Implementation of MD-5

Overview

Hash Algorithms uses when you do not want to return back any value. Mostly these algorithms uses for verification e.g. Password Confirmation. There are many algorithms which are using for this purpose; e.g. MD-5, SHA-1 and etc.

 

Example

Everyone likes to look or read complete description of that thing which he wants to work. In this example, I am using Hash algorithm MD-5 and have three methods; getMd5Hash, HashToString and verifyMd5Hash,getMd5Hash takes a parameter in bytes form that is your input data which converts input's bytes data into hash bytes. verifyMd5Hash takes two parameters one is byte data of confirmation and second is hash bytes. In it, confirmation of bytes converts into hash bytes and then parameter hash and confirmation hash data convert into two separate strings. These string uses for comparision. If true then same hash data (password) else wrong data (password).

 

Note that verifyMd5Hash returns a bool variable and System.Security.Cryptography package is using.

 

#region MD-5 Implementation

byte[] Hash_Data;

void getMd5Hash(byte[] input)

{

    // Create a new instance of the MD5CryptoServiceProvider object.

    MD5 md5Hasher = MD5.Create();

    Hash_Data = new byte[input.Length];

    // Convert the input string to a byte array and compute the hash.

    Hash_Data = md5Hasher.ComputeHash(input);

}

 

string HashToString(byte[] hdata)

{

    StringBuilder sBuilder = new StringBuilder();

    // Loop through each byte of the hashed data

    // and format each one as a hexadecimal string.

    for (int i = 0; i < hdata.Length; i++)

    {

        sBuilder.Append(hdata[i].ToString("x2"));

    }

    // Return the hexadecimal string.

    return sBuilder.ToString();

}

 

// Verify a hash against a string.

bool verifyMd5Hash(byte[] file_data, byte[] hash)

{

    getMd5Hash(file_data);

    string hashData = HashToString(hash);

    string hashOfFile = HashToString(Hash_Data);

 

    // Create a StringComparer an comare the hashes.

    StringComparer comparer = StringComparer.OrdinalIgnoreCase;

    if (0 == comparer.Compare(hashOfFile, hashData))

    {

        return true;

    }

    else

    {

        return false;

    }

}

#endregion


Similar Articles