C# - Generate MD5 hash

By , 8/23/2012
(1 ratings)
Returns the MD5 hash of a string as string.

Author: GENiALi, translation by Michael List
using System.Security.Cryptography;

/// <summary>
/// Returns a MD5 hash as a string
/// </summary>
/// <param name="TextToHash">String to be hashed.</param>
/// <returns>Hash as string.</returns>
public static String GetMD5Hash(String TextToHash)
  //Check wether data was passed
  if((TextToHash == null) || (TextToHash.Length == 0))
    return String.Empty;

  //Calculate MD5 hash. This requires that the string is splitted into a byte[].
  MD5 md5 = new MD5CryptoServiceProvider();
  byte[] textToHash = Encoding.Default.GetBytes(TextToHash);
  byte[] result = md5.ComputeHash(textToHash);

  //Convert result back to string.
  return System.BitConverter.ToString(result); 
Tagged with md5, hash, string.



Log in, to comment!