XmlDsigC14NWithCommentsTransform Class

Definition

Represents the C14N XML canonicalization transform for a digital signature as defined by the World Wide Web Consortium (W3C), with comments.

public class XmlDsigC14NWithCommentsTransform : System.Security.Cryptography.Xml.XmlDsigC14NTransform
Inheritance
XmlDsigC14NWithCommentsTransform

Examples

This section contains two code examples. The first example demonstrates how to sign an XML file using a detached signature. This example creates a signature of www.microsoft.com in an XML file and then verifies the file. The second example demonstrates how to sign an XML file using an envelope signature. This example creates a signature of an XML file and then saves the signature in new XML file.

Example #1

//
// This example signs a file specified by a URI 
// using a detached signature. It then verifies  
// the signed XML.
//

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

class XMLDSIGDetached
{
    
    [STAThread]
    static void Main(string[] args)
    {
        // The URI to sign.
        string resourceToSign = "http://www.microsoft.com";
        
        // The name of the file to which to save the XML signature.
        string XmlFileName = "xmldsig.xml";

        try
        {

            // Generate a signing key.
            RSA Key = RSA.Create();

            Console.WriteLine("Signing: {0}", resourceToSign);

            // Sign the detached resourceand save the signature in an XML file.
            SignDetachedResource(resourceToSign, XmlFileName, Key);

            Console.WriteLine("XML signature was successfully computed and saved to {0}.", XmlFileName);

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");

            //Verify the XML signature in the XML file.
            bool result = VerifyDetachedSignature(XmlFileName);

            // Display the results of the signature verification to 
            // the console.
            if(result)
            {
                Console.WriteLine("The XML signature is valid.");
            }
            else
            {
                Console.WriteLine("The XML signature is not valid.");
            }
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }

    // Sign an XML file and save the signature in a new file.
    public static void SignDetachedResource(string URIString, string XmlSigFileName, RSA Key)
    {
        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml();

        // Assign the key to the SignedXml object.
        signedXml.SigningKey = Key;

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

        // Add the passed URI to the reference object.
        reference.Uri = URIString;
        
        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new RSAKeyValue((RSA)Key));	
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false));
        xmlDigitalSignature.WriteTo(xmltw);
        xmltw.Close();
    }
    // Verify the signature of an XML file and return the result.
    public static Boolean VerifyDetachedSignature(string XmlSigFileName)
    {	
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // Load the passed XML file into the document.
        xmlDocument.Load(XmlSigFileName);
    
        // Create a new SignedXMl object.
        SignedXml signedXml = new SignedXml();

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        return signedXml.CheckSignature();
    }
}

Example #2

// This example signs an XML file using an
// envelope signature. It then verifies the 
// signed XML.

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

public class SignVerifyEnvelope
{

    public static void Main(String[] args)
    {
        try
        {
            // Generate a signing key.
            RSA Key = RSA.Create();

            // Create an XML file to sign.
            CreateSomeXml("Example.xml");
            Console.WriteLine("New XML file created."); 

            // Sign the XML that was just created and save it in a 
            // new file.
            SignXmlFile("Example.xml", "SignedExample.xml", Key);
            Console.WriteLine("XML file signed."); 

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            bool result = VerifyXmlFile("SignedExample.xml");

            // Display the results of the signature verification to \
            // the console.
            if(result)
            {
                Console.WriteLine("The XML signature is valid.");
            }
            else
            {
                Console.WriteLine("The XML signature is not valid.");
            }
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }

    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document. 
        signedXml.SigningKey = Key;

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

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)  
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
        doc.WriteTo(xmltw);
        xmltw.Close();
    }
    // Verify the signature of an XML file and return the result.
    public static Boolean VerifyXmlFile(String Name)
    {
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // Format using white spaces.
        xmlDocument.PreserveWhitespace = true;

        // Load the passed XML file into the document. 
        xmlDocument.Load(Name);

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDocument);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        return signedXml.CheckSignature();
    }

    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
    {
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode  node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");
        
        // Add some text to the node.
        node.InnerText = "Example text to be signed.";

        // Append the node to the document.
        document.AppendChild(node);

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
        document.WriteTo(xmltw);
        xmltw.Close();
    }
}

Remarks

The XmlDsigC14NWithCommentsTransform class represents the C14N XML canonicalization transform that describes the canonical form of an XML document. This transform allows a signer to create a digest using the canonical form of an XML document. A recipient can then verify the digital signature using the same canonical form of the XML document with the same transform.

Use the XmlDsigC14NWithCommentsTransform class when you need to sign an XML document that contains comments.

Note that you cannot directly create a new instance of a canonicalization transform class. To specify a canonicalization transform, pass the Uniform Resource Identifier (URI) that describes the transform to the CanonicalizationMethod property, which is accessible from the SignedInfo property. To acquire a reference to the canonicalization transform, use the CanonicalizationMethodObject property, which is accessible from the SignedInfo property.

The URI that describes the XmlDsigExcC14NWithCommentsTransform class is defined by the XmlDsigExcC14NWithCommentsTransformUrl field.

The URI that describes the XmlDsigC14NWithCommentsTransform class is defined by the XmlDsigC14NWithCommentsTransformUrl field and the XmlDsigCanonicalizationWithCommentsUrl field.

For more information about the C14N with comments transform, see Sections 6.5 and 6.6.1 of the W3C XMLDSIG specification. The canonicalization algorithm is defined in the W3C Canonical XML specification.

Constructors

XmlDsigC14NWithCommentsTransform()

Initializes a new instance of the XmlDsigC14NWithCommentsTransform class.

Properties

Algorithm

Gets or sets the Uniform Resource Identifier (URI) that identifies the algorithm performed by the current transform.

(Inherited from Transform)
Context

Gets or sets an XmlElement object that represents the document context under which the current Transform object is running.

(Inherited from Transform)
InputTypes

Gets an array of types that are valid inputs to the LoadInput(Object) method of the current XmlDsigC14NTransform object.

(Inherited from XmlDsigC14NTransform)
OutputTypes

Gets an array of types that are possible outputs from the GetOutput() methods of the current XmlDsigC14NTransform object.

(Inherited from XmlDsigC14NTransform)
PropagatedNamespaces

Gets or sets a Hashtable object that contains the namespaces that are propagated into the signature.

(Inherited from Transform)
Resolver

Sets the current XmlResolver object.

(Inherited from Transform)

Methods

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetDigestedOutput(HashAlgorithm)

Returns the digest associated with an XmlDsigC14NTransform object.

(Inherited from XmlDsigC14NTransform)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetInnerXml()

Returns an XML representation of the parameters of an XmlDsigC14NTransform object that are suitable to be included as subelements of an XMLDSIG <Transform> element.

(Inherited from XmlDsigC14NTransform)
GetOutput()

Returns the output of the current XmlDsigC14NTransform object.

(Inherited from XmlDsigC14NTransform)
GetOutput(Type)

Returns the output of the current XmlDsigC14NTransform object of type Stream.

(Inherited from XmlDsigC14NTransform)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetXml()

Returns the XML representation of the current Transform object.

(Inherited from Transform)
LoadInnerXml(XmlNodeList)

Parses the specified XmlNodeList object as transform-specific content of a <Transform> element; this method is not supported because this element has no inner XML elements.

(Inherited from XmlDsigC14NTransform)
LoadInput(Object)

Loads the specified input into the current XmlDsigC14NTransform object.

(Inherited from XmlDsigC14NTransform)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

Product Versions
.NET 8 (package-provided), 9 (package-provided)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7 (package-provided), 4.7, 4.7.1 (package-provided), 4.7.1, 4.7.2 (package-provided), 4.7.2, 4.8 (package-provided), 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9