Pergunta

We are trying to hash a xml file, i already have it working that it hashes the contents of the XML. For which i am using the following code:

        XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.Load(txtFile.Text);

        XmlNodeList list = doc.GetElementsByTagName("Document");

        XmlElement node = (XmlElement)list[0];
        //node.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        string s = node.OuterXml;

        using (MemoryStream msIn = new MemoryStream(Encoding.UTF8.GetBytes(s)))
        {
            XmlDsigC14NTransform t = new XmlDsigC14NTransform(true);
            t.LoadInput(msIn);
            using (var hash = new SHA256Managed())
            {
                byte[] digest = t.GetDigestedOutput(hash);
                txtHash.Text = BitConverter.ToString(digest).Replace("-", String.Empty);
            }
        }

however, this only hashes the contents of the XML. What i need is to hash the complete XML instead of only the contents.

If we only hash the contents, our hash doesnt compare with the control we get.

Foi útil?

Solução

You can read the file contents without creating a XmlDocument and hash the contents:

var file = File.ReadAllBytes(txtFile.Text);
using (var hash = new SHA256Managed())
{
   byte[] digest = hash.ComputeHash(file);
   txtHash.Text = BitConverter.ToString(digest).Replace("-", String.Empty);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top