System.Security.Cryptography.Xml Namespace

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

The System.Security.Cryptography.Xml namespace contains a full implementation of the World Wide Web Consortium standard for digitally signing XML data and files. In other words, the namespace helps you to sign any XML object with a digital signature. Refer to the XML-Signature Syntax and Processing page at http://www.w3.org/TR/xmldsig-core/ for details on this progressing standard.

The sample code in Listing 22.37 shows how to sign XML data and produce an envelope for it via the RSA algorithm.


Listing 22.37: SignXML1.cs, Compute Signature for XML Data


using
System;
using
System.Xml;
using
System.Security.Cryptography;
using
System.Security.Cryptography.Xml;

public
class DigitalSignSample
{
    public static void Main()
    {
        // generate XML data
        XmlDocument document = new XmlDocument();
        XmlNode node = document.CreateNode(XmlNodeType.Element, "", @"Visual Studio
.NET", "sign xml samples");
        node.InnerText = @"C# wimps the lama's bass...";
        document.AppendChild(node);
        Console.WriteLine("OriginalXML data:\r\n" + document.OuterXml + "\r\n");

        // create signedxml variable
        RSA rsa = System.Security.Cryptography.RSA.Create();
        SignedXml signedXml = new SignedXml();
        signedXml.SigningKey = rsa;

        // create dataobject
        DataObject dataObject = new System.Security.Cryptography.Xml.DataObject();
        dataObject.Data = document.ChildNodes;
        dataObject.Id = "goo";

        // add dataobject and reference
        signedXml.AddObject(dataObject);
        signedXml.AddReference(new Reference("#goo"));

        // add keyinfo
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new RSAKeyValue(rsa));
        signedXml.KeyInfo = keyInfo;

        // compute signature and get an envelope for the XML data
        signedXml.ComputeSignature();
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // output the envelope
        Console.WriteLine("====================================================");
        XmlTextWriter w = new XmlTextWriter(Console.Out);
        w.Formatting = Formatting.Indented;
        xmlDigitalSignature.WriteTo(w);
    }
}


Conclusion

Hope this article would have helped you in understanding the
System.Security.Cryptography.Xml Namespace. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Similar Articles