Active Directory Products
Calls To Calendar
SMS To CSV
SMS To Gmail
Voicemail To Gmail
How Long For Me
<< 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++)
MD5in' Tom Out.
Calculating ISO 8601 Date formats in C#, C++, and Java
Bitmasking userAccountControl attribute in LDAP from C#
Enumerating all attributes of an element and adding them to a dictionary using LINQ with Lambda Expressions
Code Analysis with NDepend V3
Writing console output from a Windows form in C#
Tom said on Thursday, August 13th, 2009 @ 7:50 AM
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: