Friday, August 09, 2013

How to: Sign XML Documents with Digital Signatures


You can use the classes in the System.Security.Cryptography.Xml namespace to sign an XML document or part of an XML document with a digital signature. XML digital signatures (XMLDSIG) allow you to verify that data was not altered after it was signed. For more information about the XMLDSIG standard, see the World Wide Web Consortium (W3C) recommendation XML Signature Syntax and Processing.

The code example in this procedure demonstrates how to digitally sign an entire XML document and attach the signature to the document in a <Signature> element. The example creates an RSA signing key, adds the key to a secure key container, and then uses the key to digitally sign an XML document. The key can then be retrieved to verify the XML digital signature, or can be used to sign another XML document.
For information about how to verify an XML digital signature that was created using this procedure, see How to: Verify the Digital Signatures of XML Documents.

To digitally sign an XML document

Create a CspParameters object and specify the name of the key container.

CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

Generate an asymmetric key using the RSACryptoServiceProvider class. The key is automatically saved to the key container when you pass the CspParameters object to the constructor of the RSACryptoServiceProvider class. This key will be used to sign the XML document.

RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

Create an XmlDocument object by loading an XML file from disk. The XmlDocument object contains the XML element to encrypt.

XmlDocument xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("test.xml");

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

SignedXml signedXml = new SignedXml(xmlDoc);

Add the signing RSA key to the SignedXml object.

signedXml.SigningKey = Key;

Create a Reference object that describes what to sign. To sign the entire document, set the Uri property to "".

// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";

Read more: MSDN