In the project that I’m working on (let’s call it BrainCredits v2.0), I wanted to integrate a user’s Gravatar into the system (like how StackOverflow does it).
To Gravatar’s credit, they make it very easy to incorporate a user’s image – just hash the user’s email address (which I have) to the end of their URL and you’ll get the image back. The email address just has to be hashed using the MD5 algorithm, and they provide examples of how to do that in PHP. Oh, it looks so easy:
echo md5( "MyEmailAddress@example.com " );
It’s a one-liner in PHP – just call md5() passing in the string you want to hash and you’ll get your hash back. There must be a similar method in C#, right? As far as I can tell, there isn’t. You have to:
- instantiate the MD5CryptoServiceProvider,
- convert your string to a byte array,
- run that byte array through the crypto provider to compute the hash (and get a byte array back)
- and instead of just converting that byte array back to a string, you need to run through each byte and convert it via this:
myByte.ToString("x2").ToLower()
Now you have your string. Lots of work, especially compared to PHP. Perhaps this is why so many developers go towards PHP? Anyway, I need to generate this hash, and decided to create an Extension Method for it. My full code looks like this:
using System.Text;
namespace System
{
public static class StringExtensions
{
public static String MD5(this String stringToHash)
{
var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] emailBytes = System.Text.Encoding.UTF8.GetBytes(stringToHash.ToLower());
byte[] hashedEmailBytes = md5.ComputeHash(emailBytes);
System.Text.StringBuilder sb = new StringBuilder();
foreach (var b in hashedEmailBytes)
{
sb.Append(b.ToString("x2").ToLower());
}
return sb.ToString();
}
}
}
You would call it like this:
String emailToHash = "dhoerster@gmail.com";
String hashedEmail = emailToHash.MD5();
Oh, that’s easy! And it makes sense.
Well, I hope this helps someone, and maybe there will be some suggestions on how to improve this. Good luck!