19 using System.Collections.Generic;
22 using System.Runtime.Serialization.Formatters.Binary;
23 using System.Security.Cryptography;
37 if (!obj.GetType().IsSerializable)
39 throw new ArgumentException(
"Object must be serializable");
42 using (MemoryStream memoryStream =
new MemoryStream())
44 BinaryFormatter binaryFormatter =
new BinaryFormatter();
47 binaryFormatter.Serialize(memoryStream, obj);
49 MD5CryptoServiceProvider checkSummer =
new MD5CryptoServiceProvider();
50 memoryStream.Seek(0, SeekOrigin.Begin);
51 return ByteArrayToHex(checkSummer.ComputeHash(memoryStream));
64 private static string ByteArrayToHex(byte[] bytes)
66 var lookup32 = _lookup32;
67 var result =
new char[bytes.Length * 2];
68 for (
int i = 0; i < bytes.Length; i++)
70 var val = lookup32[bytes[i]];
71 result[2 * i] = (char)val;
72 result[2 * i + 1] = (char)(val >> 16);
74 return new string(result);
78 #region Private methods 83 private static uint[] CreateLookup32()
85 var result =
new uint[256];
86 for (
int i = 0; i < 256; i++)
88 string s = i.ToString(
"X2");
89 result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
96 #region Private fields 98 private static readonly uint[] _lookup32 = CreateLookup32();
99 private static readonly Object _lockObject =
new Object();
static string ComputeMD5Hash(Object obj)
Computes the MD5 hash for the object, which must be serializable.