Question

Preface: I've been trying to do XML signature verification on an HTTP response, and I need help! All code is .NET 4.0 using C#.


So here's what I'm trying to accomplish:

  1. Create a signed XML document on the server
  2. Send the signed XML as body of an HTTP response
  3. Client receives the response and verifies that the signature is valid.

Server-side, I create the XML and load it into an XmlDocument. I then sign this XmlDocument object (using this example code from MSDN) and build a string from this signed XML. This string is what I send as the HTTP response body.

When my client application receives the response, it pulls the body of the response out and passes it to my signature verification function. This function builds an XmlDocument from the string, creates a SignedXml object from the XmlDocument, and retrieves the Signature to verify. Almost all this code is taken from MSDN as well (here).

Seems straightforward, right? Well my verification fails every time. I know that it's not a problem with the signing/verifying code. I've tested it in a separate app where the XML it loads is from a file, and it works perfectly. I'm even using the exact same XML to test my client/server code.

Thus, I believe the problem lies in the step where XmlDocument is converted to a string or the string is converted back to XmlDocument.

XmlDocument -> string -> XmlDocument

I've done the following things to try to make it easier to the signature to verify:

  1. Remove all tabs, newlines, carriage returns from the XML before I create the XmlDocument.
  2. Ensured that the encoding of the document is explicitly set at UTF-8 (i know from previous threads that this can cause an issue if not set).
  3. Tried generating the strings in two different ways (from OuterXML of the XmlDocument & also by using XmlWriter and StringWriter).
  4. Visually verified that the XML sent from the server is the exact same as that loaded by the client.

If you have any idea on how to remedy this problem, please help! I can post code if desired, but the only code that might be worth seeing is how I generate the string from the XmlDocument.

Was it helpful?

Solution

An old question but I figured I would would answer it for anyone else who might have encountered a similar issue. The problem was in the encoding of the string as it was sent back via the HTTP response. However, I remedied this by writing the XmlDocument directly to the response stream instead of converting it to a string first. Like such:

public void ProcessRequest(HttpContext context)
{
     // a bunch of request handling logic
     //...
     HttpResponse response = context.Response;
     XmlDocument signedXML = getTheSignedXMLData(); //the XML
     signedXML.PreserveWhitespace = true;
     signedXML.Save(response.Output);
 }

This solved by encoding issues and the signature verifies correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top