Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize object to xml and hash the result

I've been trying to serialize an object to xml and then hash the result but whenever I create the hash its always the same for different objects, not to sure what I'm doing wrong or have left out. Help would be appreciated.

Here is the code I'm using:

private static byte[] CreateHash<T>(T value)
{
    using (MemoryStream stream = new MemoryStream())
    using (SHA512Managed hash = new SHA512Managed())
    {
        XmlSerializer serialize = new XmlSerializer(typeof(T));

        serialize.Serialize(stream, value);
        return hash.ComputeHash(stream);
    }            
}
like image 344
Jonathan Avatar asked Jan 18 '23 20:01

Jonathan


2 Answers

Rewind the stream:

serialize.Serialize(stream, value);
stream.Position = 0;
return hash.ComputeHash(stream);

After Serialize, the stream is at the end, with no data available to be read.

like image 168
Marc Gravell Avatar answered Jan 23 '23 05:01

Marc Gravell


Since, a hash of nothing will always be the same hash, an initial idea would be to set the stream position back to the first byte after writing to it:

stream.Position = 0;
like image 33
Grant Thomas Avatar answered Jan 23 '23 04:01

Grant Thomas