The .Net framework has built in support for signing XML files with an XML digital signature. Here's a sample of how to create and verify an enveloped digital signature using these classes.
There are three types of XML digital signatures:
In this sample, I will create an enveloped signature over a order record recieved from a ficticous online store. The XML for that order, saved in a file order.xml is:
The first step in signing this document, is loading it into an XmlDocument object, and creating a SignedXml object for that XmlDocument:
Next, the key that will be used to sign the document must be setup. In this sample, I will just generate a random RSA key, but in reality, the website would probably have an RSA key that they would always use to sign the documents with.
The key must be set as the signing key, as well as placed in an RSAKeyValue clause. The RSAKeyValue clause puts the public portion of the keypair into the signature itself, allowing anyone who retrieves the document to validate the signature, without having to know what key was used to sign it with. The next step is to create a reference to the data being signed.
A reference with a URI that is the empty string refers to the entire containing document. However, since this is going to be an enveloped signature, validating the entire document would result in an invalid signature, since the signature value itself will be a part of the document. Therefore, we must add an XmlDsigEnvelopedSignatureTransform, which prevents the signature validator from looking at the actual signature itself when validating the document. The last step is to compute the signature, and add it to the document:
The resulting signed order looks like this:
Verifying the signature produced above is a very easy process, with the help of the SignedXml class. It involves only three steps:
The first step, loading the XML containing the signature is very similar to loading the unsigned XML above.
Next, the SignedXml class must be given the value of the signature it is to validate. This can be done by looking for elements with the tag name of Signature:
Finally, the signature needs to be checked for validity:
The above example shows how to create a signature that prevents a malicious person from modifying the contents of a CD order. However, nothing above prevents that person from reading the order and stealing the address or even credit card number of the person who placed it. In a future post, I'll show an example of using a new feature being added to Whidbey, XML Encryption, to prevent unwanted eyes from viewing this sensitive information.