Mailing List


Active Directory Products
Object Compare
Permission Compare

IPhone Products
Calls To Calendar
SMS To Gmail
Voicemail To Gmail

How Long For Me


NerdyHearn - Blog

<< Back To All Blogs

Creating an MD5 String Extension method in C#

Wednesday, August 12th, 2009

Extension methods in C# allow for some very useful additions to the base .NET string library, and I recently came across the need to have an MD5 of a string, so I figured it would be very useful to add it as an extension method.

This allows for you to use a string, defined as follows:
string temp = "My string"

And obtain the MD5 of the string by executing the following:
string md5 = temp.MD5();

Without further ado, here is the code. Please note that this will only work in .NET 3.5 and above.

public static class StringExtensions
public static string MD5(this string input)
Encoder enc = System.Text.Encoding.Unicode.GetEncoder();

byte[] rawBytes = new byte[input.Length * 2];
enc.GetBytes(input.ToCharArray(), 0, input.Length, rawBytes, 0, true);

MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(rawBytes);

StringBuilder sb = new StringBuilder();
for (int a = 0; a < result.Length; a++)

return sb.ToString();

MD5in' Tom Out.



Related Blogs

Creating an Organizational Chart using C#: Part 2
Comparing XML files in C# Using Microsoft's Diff and Patch Tool
Autostarting a Windows Service directly after install in C#
Programatically Retrieving an Assembly's PublicKeyToken through a PowerShell CmdLet
Using MOSS and WSS SharePoint Workflow to Resize Images in an Image Library


Tom said on Thursday, August 13th, 2009 @ 7:50 AM

Hi John,

Yes, you could easily do that by adding a parameter and changing the code around. In my particular case there was no need to use SHA-1 or a salted input, great idea though.


John Bubriski said on Thursday, August 13th, 2009 @ 7:40 AM

Since this is plain MD5 hashing, shouldn't you add a salt? Or maybe accept the salt as a parameter? Or you could change it to use SHA-1 for better reliability.

Tom said on Thursday, August 13th, 2009 @ 6:35 AM


That works as well, perhaps just old habits :)

Joel Lucsy said on Thursday, August 13th, 2009 @ 6:32 AM

Why not simply:
byte[] rawBytes = System.Text.Encoding.Unicode.GetBytes( input );

Add A Comment



Email Address: (not public, used to send notifications on further comments)


Enter the text above, except for the 1st and last character:

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers