Mailing List



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

Retrieving the SID of a user or group account using the Win32 SDK and C#
Calling .NET WebService From PHP
Copy a DLL from the GAC
Writing console output from a Windows form in C#
Reading an XML file using LINQ


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