Previous post move issues related to the signing of documents. This entry, however, did not close topic, because it does not show how to verify a signed document. This subject will try to move in this entry.

Verification of the signed document, it seems much simpler than signing. In order to check a document, only to find an element Signature and check, whether the signature contained in the document corresponds to original document. Immediately add the assumption, that the document, in which the different number of elements Signature than one, I think it is incorrect. In addition, for, when the XML document does not contain information allowing the verification of signatures should be complemented.

This function verifies the authenticity of the document by verifying the signature may look as follows:

/// <summary>
/// Checks if document has valid XML signature
/// </summary>
/// <param name="xmlDocument">Document to check</param>
/// <param name="key">Key which XML signature should be checked</param>
/// <returns>Valid of signature</returns>
public static bool CheckXmlSignature(XmlDocument xmlDocument, AsymmetricAlgorithm key)
{
   if (xmlDocument == null)
   {
      throw new ArgumentNullException("xmlDocument");
   }

   if (key == null)
   {
      throw new ArgumentNullException("key");
   }

   // Create a new SignedXml object and pass it
   // the XML document class.
   SignedXml signedXml = new SignedXml(xmlDocument);

   // Find the "Signature" node and create a new
   // XmlNodeList object.
   XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

   if (nodeList.Count == 1)
   {
      // Load the signature node.
      signedXml.LoadXml((XmlElement)nodeList[0]);

      // Check the signature and return the result.
      return signedXml.CheckSignature(key);
   }
   else
   {
      return false;
   }
}

In the above method, signed document is checked, where there is no information allowing the signature to verify the correctness. Therefore, this information is supplemented by a parameter key. In the case, when XML document contains the information that helps to verify the signature in the above method should be changed only one line:

From:

return signedXml.CheckSignature(key);

To:

return signedXml.CheckSignature();

In this case, you should also remove useless parameter of the method – AsymmetricAlgorithm key.