NerdyHearn
Home
Blog
Software

Contact
Mailing List

IPhone Products
SMS To Gmail
Voicemail To Gmail
Calls To Calendar

Other Products
TiffWizard

Sites
SaveMySerials
How Long For Me
DocuTerminal

Blog
Twitter

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++)
{
sb.Append(result[a].ToString("X2"));
}

return sb.ToString();
}
}

MD5in' Tom Out.

Tags

CSharp

Related Blogs

Calculating ISO 8601 Date formats in C#, C++, and Java
Validate a Windows Username and Password against Active Directory
Resizing Images in C#

A quick way to find C++ method signatures for C# Interop

Comments

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.

Tom

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

@Joel,

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

Name:


URL:


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


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. DocuTerminal - Online Filing Cabinet solution. Scan, search and archive your paper documents. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers SubSonos - Stream your subsonic music collection to your Sonos wireless system