An easy way to calculate an MD5 hash

Posted: (EET/GMT+2)

 

It is sometimes necessary to calculate hash values, and personally I prefer the MD5 algorithm.

I once had an Win32 MD5 implementation in Delphi code, but now with .NET, I don't need to write the code myself anymore.

Instead, I can use simple code like the following. The idea is to read an input string from a textbox, and show the hexadecimal hash string in another:

procedure MyForm.Button1_Click(sender: System.Object; e: System.EventArgs);
Var
  InputBytes : Array of Byte;
  AE         : System.Text.ASCIIEncoding;
  MD5        : System.Security.Cryptography.MD5CryptoServiceProvider;
  HashBytes  : Array of Byte;

begin
  AE := System.Text.ASCIIEncoding.Create();
  InputBytes := AE.GetBytes(TextBox1.Text);
  MD5 := System.Security.Cryptography.MD5CryptoServiceProvider.Create();
  HashBytes := MD5.ComputeHash(InputBytes);
  TextBox2.Text := ByteArrayToHexString(HashBytes);
end;

Here, the code uses the MD5CryptoServiceProvider class from the System.Security.Cryptography namespace, as indicated by the Microsoft KB article 307020.

Finally, you need a way to convert a byte array to a hexadecimal string:

function MyForm.ByteArrayToHexString(Arr: array of Byte): String;
Var
  SB : System.Text.StringBuilder;
  B  : Byte;
  I  : Integer;

begin
  SB := System.Text.StringBuilder.Create(&Array(Arr).Length*2);
  For I := 0 to System.&Array(Arr).Length-1 do Begin
    B := Arr[I];
    SB.Append(B.ToString('X2'));
  End;
  Result := SB.ToString();
end;

I would love to see a simple way of doing this conversion, but I'm yet to find a class to convert a byte array to a hex string.