bovender framework
C# framework that implements MVVM and more
CommonHelpers.cs
1 /* CommonHelpers.cs
2  * part of Bovender framework
3  *
4  * Copyright 2014-2018 Daniel Kraus
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 using System;
19 using System.Collections.Generic;
20 using System.IO;
21 using System.Linq;
22 using System.Runtime.Serialization.Formatters.Binary;
23 using System.Security.Cryptography;
24 using System.Text;
25 
26 namespace Bovender
27 {
28  public static class CommonHelpers
29  {
35  public static string ComputeMD5Hash(Object obj)
36  {
37  if (!obj.GetType().IsSerializable)
38  {
39  throw new ArgumentException("Object must be serializable");
40  }
41 
42  using (MemoryStream memoryStream = new MemoryStream())
43  {
44  BinaryFormatter binaryFormatter = new BinaryFormatter();
45  lock (_lockObject)
46  {
47  binaryFormatter.Serialize(memoryStream, obj);
48  }
49  MD5CryptoServiceProvider checkSummer = new MD5CryptoServiceProvider();
50  memoryStream.Seek(0, SeekOrigin.Begin);
51  return ByteArrayToHex(checkSummer.ComputeHash(memoryStream));
52  }
53  }
54 
55 
64  private static string ByteArrayToHex(byte[] bytes)
65  {
66  var lookup32 = _lookup32;
67  var result = new char[bytes.Length * 2];
68  for (int i = 0; i < bytes.Length; i++)
69  {
70  var val = lookup32[bytes[i]];
71  result[2 * i] = (char)val;
72  result[2 * i + 1] = (char)(val >> 16);
73  }
74  return new string(result);
75  }
76 
77 
78  #region Private methods
79 
83  private static uint[] CreateLookup32()
84  {
85  var result = new uint[256];
86  for (int i = 0; i < 256; i++)
87  {
88  string s = i.ToString("X2");
89  result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
90  }
91  return result;
92  }
93 
94  #endregion
95 
96  #region Private fields
97 
98  private static readonly uint[] _lookup32 = CreateLookup32();
99  private static readonly Object _lockObject = new Object();
100 
101  #endregion
102  }
103 }
static string ComputeMD5Hash(Object obj)
Computes the MD5 hash for the object, which must be serializable.