C# create MD5 hash from a string

A common task when dealing with sensitive data is to create a hash of it. MD5 is used quite often especially when dealing with password, etc. I will leave the discussion of collisions, etc to others and just show a function that will return an array of bytes that is the result of hashing the input string. This function calls for an Encoding object to be passed in since you never know what encoding you will be using. But you could easily hard code the encoding if you know that will never change.

using System.Security.Cryptography;

/// <summary>
/// Hashes the string.
/// </summary>
/// <param name="valueToHash">The value to hash.</param>
/// <param name="textEncoding">The text encoding.</param>
/// <returns></returns>
private byte[] HashString( String valueToHash, Encoding textEncoding )
{
   byte[] result;

   using( MD5 md5 = MD5.Create() )
   {
      byte[] inputBytes = textEncoding.GetBytes( valueToHash );
      result = md5.ComputeHash( inputBytes );
   }

   return result;

}

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC