The following method returns the MD5 hash for any given string. For instance for a password. It might be of some assistance when you’re trying to validate user credentials but you don’t want to store the password readable in the database.

For this method, you’ll need the following using statements:

using System;
using
System.Text;
using
System.Security.Cryptography;



public
string EncodePassword(string originalPassword)
{
  //Declarations
  Byte[] originalBytes;
  Byte[] encodedBytes;
  MD5 md5;

  //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
  md5 = new
MD5CryptoServiceProvider();
  originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
  encodedBytes = md5.ComputeHash(originalBytes);

  //Convert encoded bytes back to a ‘readable’ string
  return
BitConverter.ToString(encodedBytes);
}

Hmmm… I seem to write comments when I’m trying to explain something 😉