Friday, August 14, 2009

GetHashCode using MD5

Wanted to have a way to get a hash code for an object, and the code will be different when the data within the object changes. Only supported for objects that support serialization... but it is better then nothing...

public static class HashCodeGenerator
public static string GetMD5HashCode(this object obj)
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
var data = stream.ToArray();
StringBuilder sBuilder = new StringBuilder();

// get the hash code of the object.
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
var hashBytesArray = md5.ComputeHash(data);

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < hashBytesArray.Length; i++)

return sBuilder.ToString();

public static bool CompareMD5HashCode(this object obj, string hashCode)
string hash = obj.GetMD5HashCode();
bool isMatch = false;
if (hash == hashCode)
isMatch = true;

return isMatch;

No comments: