views:

373

answers:

2

What's the best way to go about hashing an XML document in C#? I'd like to hash an XML document so that I can tell if it was manually changed from when it was generated. I'm not using this for security--it's OK if someone changes the XML, and changes the hash to match.

For example, I'd hash the child nodes of the root and store the hash as an attribute of the root:

<RootNode Hash="abc123">
    <!-- Content to hash here -->
</RootNode>
+3  A: 

You can use the cryptography name space:

System.Security.Cryptography.MACTripleDES hash = new System.Security.Cryptography.MACTripleDES(Encoding.Default.GetBytes("mykey"));
string hashString = Convert.ToBase64String(hash.ComputeHash(Encoding.Default.GetBytes(myXMLString)));

You just need to use a key to create the hashing cryptographer and then create a hash with the string reqpresentation of your xml.

Matt Wrock
see also System.Security.Cryptography.MD5, System.Security.Cryptography.SHA1, System.Security.Cryptography.SHA256, etc. and review comparision here: http://en.wikipedia.org/wiki/Cryptographic_hash_function
csharptest.net
Encoding.Default is the encoding for the operating system's current ANSI code page. Your code will therefore give different results depending on the settings in the Regional and Language Options - Advanced tab.
Wim Coenen
wcoenen has a very fair point. Use Encoding.ASCII or Encoding.<some consistent encoding>.
Matt Wrock
+3  A: 

.NET has classes that implement the XML digital signature spec. The signature can be added inside the original XML document (i.e. an "enveloped signature"), or stored/transferred separately.

It may be a bit overkill since you don't need the security, but it has the advantage of being already implemented, and being a standard which does not depend on a language or platform.

Wim Coenen
I like this solution, because as you pointed out, it is already implemented and is a standard.
emddudley