Using the System. Security. Cryptography. Xml Namespace


Using the System. Security. Cryptography. Xml Namespace

Cryptography is an extremely important part of data communications, especially as companies move into the Internet environment to communicate with partners and customers better.

Chapter 7 discusses many of the issues surrounding cryptography. The problem is that many cryptographic techniques would prove difficult to use with XML because XML is structured text—not pure text. The structure is important to the interpretation of the data XML provides. Consequently, the .NET Framework provides the special System.Security.Cryptography.Xml namespace to make working with XML easier.

When you look at the cryptographic examples in Chapter 7, you’ll notice that the data is unreadable. You could use this method to transmit an XML document that didn’t require immediate processing on the other side. XML is structured data, so readability is important when immediate interpretation is required. Consequently, signing the document so that tampering is immediately obvious is the next best choice. No, signing won’t protect your data, but it does make it less likely that someone will change the data or even add a virus to it. The cryptographic techniques in Chapter 7 will work just as well for XML as they will for any other file when data hiding is important. The technique in this section of the chapter demonstrates how to sign a file so that tampering is immediately apparent. You could use this technique to ensure the integrity of transactions, such as those created by an application that relies on SOAP.

The following sections help you understand the role of the System.Security.Cryptography .Xml namespace better. These sections describe what makes this namespace different from other cryptographic functionality discussed earlier in the book. However, if you don’t already know how to use cryptographic techniques, you’ll want to read Chapter 7 first.

Understanding the System.Security.Cryptography.Xml Namespace

The System.Security.Cryptography.Xml namespace looks somewhat complicated until you start to break it into pieces. The important thing to remember is that this namespace augments the functionality provided by the System.Security.Cryptography namespace. For example, when you need a key to compute a signature, you’ll use a standard RSACryptoServiceProvider object, just like what’s shown in the examples in Chapter 7 (see Listing 7.4 for the first example of how to use such a key). You can easily divide the classes in this namespace into three areas.

Key Management Cryptography in all its forms relies on keys. When you work with Web services, you need some method of managing keys with parties that you might never meet. As you’ll see in the example, the key management features in classes such as KeyInfo and Reference make it possible to work with third parties in a secure manner.

Data Management At some point, you’ll need to modify the original data to include a signature. The data management features of classes such as SignedXml make it possible to generate, maintain, and output a signed document without affecting the content of the original document.

Data Transformation You’ll use one of several transforms to add the signature to the document. The transform defines the appearance of the signature within the document. Use a different transform and the signature will have a different appearance. Most of the transforms provided with the .NET Framework follow the World Wide Web Consortium (W3C) guidelines.

Creating and Verifying XML Digital Signatures

The example in this section performs two tasks. First, it reads a standard XML file from disk, calculates a signature for it, and writes the resulting signed document to disk. Second, it reads the signed XML file from disk, verifies the signature, and reports whether the document remains unchanged or not. Listing 11.4 shows the essential code for both tasks. However, this listing isn’t complete. You’ll find the complete source code for this example in the \Chapter 11\C#\XMLCrypto and \Chapter 11\VB\XMLCrypto folders of the source code located on the Sybex Web site. The \Chapter 11\Sample XML Data folder contains the sample data for this example.

Listing 11.4 Signing and Verifying an XML File

start example
private void btnSign_Click(object sender, System.EventArgs e) {    XmlDocument                         Doc;        // The XML document.    SignedXml                           SignedDoc;  // Signed document.    Reference                           RefDoc;     // Reference doc.    Transform                           Trans;      // Doc Tranform.    XmlDsigEnvelopedSignatureTransform  EnvTrans;   // Env Transform.    KeyInfo                             KeyData;    // RSA Key Data.    XmlElement                          XmlSig;     // XML Signature.    XmlTextWriter                       Writer;     // XML File Writer.    // Create the document and load the file.    Doc = new XmlDocument();    Doc.Load(new XmlTextReader(txtInput.Text));    // Create the signed document.    SignedDoc = new SignedXml(Doc);    // Add the key to the signed document.    SignedDoc.SigningKey = RSACrypto;    // Create the reference document.    RefDoc = new Reference();    RefDoc.Uri = "";    Trans = new XmlDsigC14NWithCommentsTransform();    RefDoc.AddTransform(Trans);    EnvTrans = new XmlDsigEnvelopedSignatureTransform(true);    RefDoc.AddTransform(EnvTrans);    // Add the reference to the signed document.    SignedDoc.AddReference(RefDoc);    // Add key information to the signed document.    KeyData = new KeyInfo();    KeyData.AddClause(new RSAKeyValue((RSA)RSACrypto));    SignedDoc.KeyInfo = KeyData;    // Compute the signature value and add it to an element.    SignedDoc.ComputeSignature();    XmlSig = SignedDoc.GetXml();    // Add the element to the document.    Doc.DocumentElement.AppendChild(Doc.ImportNode(XmlSig, true));    // Remove the XML declaration if necessary.    if (Doc.FirstChild is XmlDeclaration)       Doc.RemoveChild(Doc.FirstChild);    // Save the document to disk.    Writer = new XmlTextWriter(txtSigned.Text, new UTF8Encoding(false));    Doc.WriteTo(Writer);    Writer.Close(); } private void btnValdiate_Click(object sender, System.EventArgs e) {    XmlDocument Doc;        // The XML document.    SignedXml   Signed;     // Holds the signed XML.    XmlNodeList SignNode;   // Contains the signature node.    // Create the document and load the file.    Doc = new XmlDocument();    Doc.Load(txtSigned.Text);    // Define a signed XML object.    Signed = new SignedXml(Doc);    // Get the signed node.    SignNode = Doc.GetElementsByTagName("Signature");    Signed.LoadXml((XmlElement)SignNode[0]);    // Verify the signature.    if (Signed.CheckSignature())       MessageBox.Show("The Signature is Verified",                       "Check Signature",                       MessageBoxButtons.OK,                       MessageBoxIcon.Information);    else       MessageBox.Show("Error in Signature",                       "Check Signature",                       MessageBoxButtons.OK,                       MessageBoxIcon.Error); }
end example

Signing the document is a lot more complicated than verifying the signature. The btnSign_Click() method begins by loading the document into memory using an XmlTextReader. It then uses the original document found in Doc to create a SignedXml object. This section object performs data manipulation tasks such as calculating the signature value for the input document shown in Figure 11.3.

click to expand
Figure 11.3: The input document is a basic XML file.

The code creates a Reference object next. You can look at the Reference object in a number of ways, but the easiest method is as a reference document—essentially a guide the program will use to create the signature. The code begins by defining an empty Uri property value. It’s possible to set a URI as a definition document, but the example builds the information from scratch. Make certain you set the Uri property to an empty value or you’ll end up with odd null reference error messages. The code defines two transforms for the signature. The first, XmlDsigC14NWithCommentsTransform, defines the canonicalization or data presentation transform. The second, XmlDsigEnvelopedSignatureTransform, defines the data envelope. The code adds the Reference object to SignedDoc for use in generating the signature.

At this point, the code has defined rules for creating a signature. It now adds a key for generating the signature. This is the same key used in Chapter 7 for asymmetric cryptography.

The public key will appear as part of the signed document so that any third party can verify the signature. You can also make the public key available in a public place so third parties can verify that no one has changed keys and signed the document a second time.

The code generates a signature, at this point, and adds it to the original document in memory. The code removes the XML declaration to show that this document no longer follows the standard XML format (it contains a signature) and writes the data to disk. Figure 11.4 shows the output of the program.

click to expand
Figure 11.4: Creating a signed document means no one can change the content without also changing the signature.

The original data is still intact. However, notice that the file now contains signature information. The btnValdiate_Click() method validates this code—a simple procedure. Any change to the file in Figure 11.4 at all will cause the validation to fail. In addition, the file contains the public key value, making it possible to check the key as well for modification.

The code begins by loading the signed XML document. It uses this document to create a SignedXml object similar to the one used to create the original signature. The code also loads the signature element and places it in the SignedXml object. The code completes the process by calling the Signed.CheckSignature() method. A true return value means that the file is unchanged.

start sidebar
Global XML Architecture

At some point, you’re going to hear Microsoft talk about Global XML Architecture (GXA). At first, you might think this is yet another in a long line of Microsoft technologies such as Distributed Network Architecture (DNA) that could affect application development at a conceptual level. However, all that Microsoft has done is package the Web technologies discussed in this book into a more convenient form.

From a security perspective, GXA doesn’t add anything new you need to consider as part of your application development strategy. The same security holes discussed in other parts of the chapter for other Web technologies also appear in GXA. You’ll also find that .NET will work the same from a security perspective as it does with any other Web technology. (The chapter doesn’t consider the productivity, reliability, or other benefits that GXA does provide.)

You can see an overview of GXA at http://msdn.microsoft.com/library/en-us/dngxa/html/gloxmlws500.asp. Don Box provides another, more technical, view of GXA at http://msdn.microsoft.com/library/en-us/dngxa/html/understandgxa.asp. If you’d like to see some typical case studies for GXA, try the Got Dot Net site at (http://www.gotdotnet.com/team/XMLwebservices/gxa_overview.aspx). For a list of GXA related links, check out http://msdn.microsoft.com/webservices/understanding/gxa/.

end sidebar




.Net Development Security Solutions
.NET Development Security Solutions
ISBN: 0782142664
EAN: 2147483647
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net