144-c-sharp-md5-hash-code-example

C# md5 hash code can be easily obtained by using following namespaces:

  • System.Security.Cryptography;
  • System.Globalization;
  • System.IO;

If we want to calculate md5 hash that is 32 characters long string of any input for simple string, we can do it with just one line of code:

string md5hash = CreateMD5Hash(txtInput.Text);

The other, longer but educational way is to convert string into byte array and then to call MD5 object method for creating hash 32 bytes.

MD5 md5Object = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(txtInput.Text);
byte[] outputHashBytes = md5Object.ComputeHash(inputBytes);

Now, all we need is to turn 32 long array of hash bytes into hex format string:

string str_hash = “”;
for (int i = 0; i < outputHashBytes.Length; i++)
{

str_hash += outputHashBytes[i].ToString(“X2”);

}

Similar approach is when we want to calculate md5 hash code for binary file.

FileStream fs_Read = new FileStream(openFileDialog1.FileName,FileMode.Open);
var var_data_size = (int)fs_Read.Length;
byte[] bytes_to_read = new byte[var_data_size];
fs_Read.Read(bytes_to_read,0,var_data_size);
fs_Read.Close();

MD5 md5Object = System.Security.Cryptography.MD5.Create();
byte[] outputHashBytes = md5Object.ComputeHash(bytes_to_read);

string str_hash = “”;
for (int i = 0; i < outputHashBytes.Length; i++)
{

str_hash += outputHashBytes[i].ToString(“X2”);

}

External links:

C# hash md5 code on Codeproject

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*