Max Kilovatiy
Max Kilovatiy

Reputation: 798

Different DigestValue for the same XML document

I have signed xml document here

The digest value of the document is atHP855e32qDMu4fzAZr+wXRqfeLh9HTpnAlAFy/jDg= When I try to check it with code below the result is Ppk6zE8XY4zaIPco/fY/sSKog3imkmko8CMAIHVNwTw= I think the problem is in Body tag that contain whitespaces. If sign this document without whitespaces, digest values are equal.

Who can spot a mistake?

public static byte[] GetDigest(XmlDocument doc)
    {
        var nodeList = doc.GetElementsByTagName(
          "Signature", "http://www.w3.org/2000/09/xmldsig#");

        var signedXml = new SignedXml(doc);
        signedXml.LoadXml((XmlElement)nodeList[0]);

        var signatureDescription = CryptoConfig.CreateFromName(signedXml.SignedInfo.SignatureMethod) as SignatureDescription;
        var hashAlgorithm = signatureDescription.CreateDigest();

        var xmlDocument = new XmlDocument
        {
            PreserveWhitespace = true
        };

        var body = doc.SelectSingleNode("/ReportEnvelope/Body");

        XmlNodeList transformNode = ((XmlElement)(nodeList[0])).GetElementsByTagName("Transform");

        xmlDocument.AppendChild(xmlDocument.ImportNode(body, true));

        var transform = signedXml.SignedInfo.CanonicalizationMethodObject;
        transform.LoadInnerXml(transformNode);
        transform.LoadInput(xmlDocument);
        return transform.GetDigestedOutput(hashAlgorithm);
    }

Upvotes: 1

Views: 1519

Answers (1)

MichaelChan
MichaelChan

Reputation: 1836

I encountered this issue as well and it has something to do with how SignedXml creates the hash digest. In .NET 4, it completely ignores any whitespace in the the XML.

SignedXml.CheckSignature fails in .NET 4 but it works in .NET 3.5, 3 or 2

Upvotes: 1

Related Questions