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();
by开发者_高级运维te[] 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?
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).
The whole stringbuilder thing is a way of converting the bytes into a hex string (e.g. convert 16 bytes into 32 chars). See How do you convert Byte Array to Hexadecimal String, and vice versa? for a variety of other ways to accomplish the same thing.
精彩评论