DevPinoy.org
A Filipino Developers Community
   
How To: Convert a string to MD5 in .NET

I was working on a .NET application that integrates with Gravatar today because I needed a quickway to fetch someone's photo based on their email address. One requirement when doing this type of integration with Gravatar is that the email should be encrypted into an MD5 hash. Luckily, .NET already has a library that can do this for me by just calling a few methods:

[C# Version]

public static string ToMD5(string stringToConvert)
{
   //create an instance of the MD5CryptoServiceProvider
   MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

   //convert our string into byte array
   byte[] byteArray = Encoding.UTF8.GetBytes(stringToConvert);

   //get the hashed values created by our MD5CryptoServiceProvider
   byte[] hashedByteArray = md5Provider.ComputeHash(byteArray);

   //create a StringBuilder object
   StringBuilder stringBuilder = new StringBuilder();

   //loop to each each byte
   foreach (byte b in hashedByteArray)
   {
      //append it to our StringBuilder
      stringBuilder.Append(b.ToString("x2").ToLower());
   }

   //return the hashed value
   return stringBuilder.ToString();
}

[VB.NET Version]

Public Shared Function ToMD5(ByVal stringToConvert As String) As String 
   'create an instance of the MD5CryptoServiceProvider 
   Dim md5Provider As New MD5CryptoServiceProvider() 

   'convert our string into byte array 
   Dim byteArray As Byte() = Encoding.UTF8.GetBytes(stringToConvert) 

   'get the hashed values created by our MD5CryptoServiceProvider 
   Dim hashedByteArray As Byte() = md5Provider.ComputeHash(byteArray) 

   'create a StringBuilder object 
   Dim stringBuilder As New StringBuilder() 

   'loop to each each byte 
   For Each b As Byte In hashedByteArray 
      'append it to our StringBuilder 
      stringBuilder.Append(b.ToString("x2").ToLower()) 
   Next 

   'return the hashed value 
   Return stringBuilder.ToString()
End Function

Now all I need to do is get the result of my function and pass it to the avatar page in the Gravatar website and it should return me my Gravatar image.

[C# Version]

string gravatarUrl = "http://www.gravatar.com/avatar.php?gravatar_id";
string gravatarID = Utilities.Strings.ToMD5("keith.rull@gmail.com");
Image1.ImageUrl = String.Format("{0}={1}",gravatarUrl,gravatarID);

[VB.NET Version]

Dim gravatarUrl As String = "http://www.gravatar.com/avatar.php?gravatar_id"
Dim gravatarID As String = Utilities.Strings.ToMD5("keith.rull@gmail.com")
Image1.ImageUrl = [String].Format("{0}={1}", gravatarUrl, gravatarID)

http://www.gravatar.com/avatar.php?gravatar_id=d7ae6b890f16ad7541732e0f38adcbf2

Awesome!


Posted 12-26-2007 11:20 AM by keithrull
Copyright DevPinoy 2005-2008