Creating a hash of an XML document in C #

What is the best way to do hashing an XML document in C #? I would like to hash an XML document so that I can determine if it has been manually modified since it was created. I do not use this for security - it’s normal if someone changes the XML and changes the hash to match.

For example, I would haveh child nodes of the root and save the hash as a root attribute:

<RootNode Hash="abc123"> <!-- Content to hash here --> </RootNode> 
+7
c # xml hash canonicalization
source share
3 answers

.NET has classes that implement the XML digital signature specification . The signature may be added to the original XML document (ie, “Enveloped Signature”) or stored / transmitted separately.

It may be a little outwit, because you do not need security, but it has the advantage that it has already been implemented, and is a standard that does not depend on the language or platform.

+7
source share

You can use the cryptography namespace:

 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 the key to create a hash cryptograph, and then create a hash with a string representation of your xml.

+4
source share

Add the .NET link to System.Security and use XmlDsigC14NTransform. Here is an example ...

 /* http://www.w3.org/TR/xml-c14n Of course is cannot detect these are the same... <color>black</color> vs. <color>rgb(0,0,0)</color> ...because that dependent on app logic interpretation of XML data. But otherwise it gets the following right... •Normalization of whitespace in start and end tags •Lexicographic ordering of namespace and attribute •Empty element conversion to start-end tag pair •Retain all whitespace between tags And more. */ public static string XmlHash(XmlDocument myDoc) { var t = new System.Security.Cryptography.Xml.XmlDsigC14NTransform(); t.LoadInput(myDoc); var s = (Stream)t.GetOutput(typeof(Stream)); var sha1 = SHA1.Create(); var hash = sha1.ComputeHash(s); var base64String = Convert.ToBase64String(hash); s.Close(); return base64String; } 
+2
source share

All Articles