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?