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);
}
}
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With