Get MD5 of Serializable Class
Hello.
I have a class that is serializable. I would like to compute the MD5 of it.
I already had a function in the project to get a MD5 from a Stream, so I reused it, and created a function to convert an object to a memorystream.
The code is as follows. Does anyone see any problems, but more to the point, is there an easier way to do this that I'm simply missing?
Thanks in advance.
Code:
Private Function GetMD5FromObject(ByVal obj As Object) As String
Dim msObjectStream As MemoryStream = ObjectToMemoryStream(obj)
Dim strHashFromObject As String = GetMD5FromStream(msObjectStream)
msObjectStream.Close()
Return strHashFromObject
End Function
Private Function GetMD5FromStream(ByVal mStream As System.IO.MemoryStream) As String
Dim strHash As String
Using md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
mStream.Position = 0
' hash contents of this stream
Dim hash() As Byte = md5.ComputeHash(mStream)
' return formatted hash
strHash = ByteArrayToString(hash)
End Using
Return strHash
End Function
Function ObjectToMemoryStream(ByVal obj As Object) As MemoryStream
' Create a memory stream and a formatter.
Dim ms As New System.IO.MemoryStream(1000)
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(Nothing, _
New System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Clone))
' Serialize the object into the stream.
bf.Serialize(ms, obj)
' Position streem pointer back to first byte.
ms.Seek(0, SeekOrigin.Begin)
' Return the ms
Return ms
End Function
Re: Get MD5 of Serializable Class
If it works just fine I would not worry about it.
Re: Get MD5 of Serializable Class
It does work. I just thought maybe I was missing something...
It seems like the 'long way', but it maybe the shortest/safest route...