views:

78

answers:

2

I was looking for extension methods and stumbled in to a function that claims to mimic how PHP does the MD5 functions. Here's an exact copy(I don't get why the declaration and initialization of the Crypto were done separately...)

public static string MD5(this string s) {
    MD5CryptoServiceProvider provider;
    provider = new MD5CryptoServiceProvider();
    byte[] bytes = Encoding.UTF8.GetBytes(s);
    StringBuilder builder = new StringBuilder();

    bytes = provider.ComputeHash(bytes);

    foreach(byte b in bytes) {
        builder.Append(b.ToString("x2").ToLower());
    }

    return builder.ToString();
}

The MSDN library shows this as being the way to do it:

byte[] MD5hash (byte[] data) {
   // This is one implementation of the abstract class MD5.
   MD5 md5 = new MD5CryptoServiceProvider();

   byte[] result = md5.ComputeHash(data);

   return result;
}

Except for the argument being a string, what's the need for the stringbuilder and appending each byte? If I just do Encoding.UTF8.GetBytes on the string, I should have a byte array, usable for the method found in the MSDN library.

Can anyone point to a use for the extension method?

+3  A: 

The first method returns the hexadecimal encoding of the result. The latter returns it has a byte[] without encoding it as hex in a string.

The former is more of a convenience method when returning the result as a string (perhaps in a URL, form, etc).

Yann Ramin
+1 And the first method also takes a hex string as a parameter rather than a byte array.
Mark Byers
A: 

The whole stringbuilder thing is a way of converting the bytes into a hex string (e.g. convert 16 bytes into 32 chars). See http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c for a variety of other ways to accomplish the same thing.

Gabe