.netSecurity

Verify the Digital Signatures of XML Documents in C#

In this article, we will discuss on how to verify digital signatures of XML documents in C#.

You can use the classes in the System.Security.Cryptography.Xml namespace to verify XML data signed with a digital signature. XML digital signatures (XMLDSIG) allow you to verify that data was not altered after it was signed

The code example in this procedure demonstrates how to verify an XML digital signature contained in a element. The example retrieves an RSA public key from a key container and then uses the key to verify the signature.

Verify the Digital Signature:
To verify the document, you must use the same asymmetric key that was used for signing. Create a CspParameters object and specify the name of the key container that was used for signing.

Retrieve the public key using the RSACryptoServiceProvider class. The key is automatically loaded from the key container by name when you pass the CspParameters object to the constructor of the RSACryptoServiceProvider class.

Create an XmlDocument object by loading an XML file from disk. The XmlDocument object contains the signed XML document to verify.

Create a new SignedXml object and pass the XmlDocument object to it.

Find the element and create a new XmlNodeList object. XmlNodeList nodeList = Doc.GetElementsByTagName(“Signature”);

Load the XML of the first element into the SignedXml object.

Check the signature using the CheckSignature method and the RSA public key. This method returns a Boolean value that indicates success or failure.

Example:
This example assumes that a file named “test.xml” exists in the same directory as the compiled program. The “test.xml” file must be signed using the techniques described in How to: Sign XML Documents with Digital Signatures.

© 2015, www.techkatak.com. All rights reserved.