Cyber Security & Dot Net Security

Thursday, September 23, 2010

HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

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);
}

No comments: