Export (0) Print
Expand All
0 out of 1 rated this helpful - Rate this topic

XmlDsigEnvelopedSignatureTransform Class

Represents the enveloped signature transform for an XML digital signature as defined by the W3C.

Namespace: System.Security.Cryptography.Xml
Assembly: System.Security (in system.security.dll)

public class XmlDsigEnvelopedSignatureTransform : Transform
public class XmlDsigEnvelopedSignatureTransform extends Transform
public class XmlDsigEnvelopedSignatureTransform extends Transform

The XmlDsigEnvelopedSignatureTransform class removes the <Signature> element from an XML document before the digest is computed. With this transform, you can sign and verify all elements of an XML document except the XML digital signature elements.

Although you can create and insert a signature into an XML document, verifying the modified document using the embedded signature will fail because the document now has additional elements. This transform removes the <Signature> element and allows you to verify the document using its original form.

Use the XmlDsigEnvelopedSignatureTransform class whenever you create an enveloped signature.

For more information about the enveloped signature transform, see Section 6.6.4 of the XMLDSIG specification, which is available from the W3C at www.w3.org/TR/xmldsig-core/.

This section contains two code examples. The first example demonstrates how to sign an XML file using an envelope signature. The second example demonstrates how to use members of the XmlDsigEnvelopedSignatureTransform class.

Example #1

//
// 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.X509Certificates;
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.
            RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

            // 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();
    }
}

//
// This example signs an XML file using an
// envelope signature. It then verifies the 
// signed XML.
//
import System.*;
import System.Security.Cryptography.*;
import System.Security.Cryptography.X509Certificates.*;
import System.Security.Cryptography.Xml.*;
import System.Text.*;
import System.Xml.*;

public class SignVerifyEnvelope
{
    public static void main(String[] args)
    {
        try {
            // Generate a signing key.
            RSACryptoServiceProvider key = new RSACryptoServiceProvider();

            // 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...");

            boolean result = VerifyXmlFile("SignedExample.xml").booleanValue();

            // 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.get_Message());
        }
    } //main

    // 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.set_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.set_SigningKey(key);

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

        // Add a transformation to the reference.
        Transform trns = new XmlDsigC14NTransform();

        reference.AddTransform(trns);

        // 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.set_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.get_DocumentElement().AppendChild(doc.ImportNode(
            xmlDigitalSignature, true));
        if (doc.get_FirstChild() instanceof XmlDeclaration) {
            doc.RemoveChild(doc.get_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();
    } //SignXmlFile   

    // 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.set_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.get_ItemOf(0))));

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

    // 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.set_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();
    } //CreateSomeXml
} //SignVerifyEnvelope

Example #2

using System;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;

class Class1
{
    private static string Certificate =  "..\\..\\my509.cer";

    [STAThread]
    static void Main(string[] args)
    {
        // Encrypt an XML message
        XmlDocument productsXml = LoadProducts();
        ShowTransformProperties(productsXml);

        SignDocument(ref productsXml);
        ShowTransformProperties(productsXml);

        // Use XmlDsigEnvelopedSignatureTransform to resolve a Uri.
        Uri baseUri = new Uri("http://www.contoso.com");
        string relativeUri = "xml";
        Uri absoluteUri = ResolveUris(baseUri, relativeUri);

        Console.WriteLine("This sample completed successfully; " +
            "press Enter to exit.");
        Console.ReadLine();
    }

    // Encrypt the text in the specified XmlDocument.
    private static void ShowTransformProperties(XmlDocument xmlDoc)
    {
        XmlDsigEnvelopedSignatureTransform xmlTransform = 
            new XmlDsigEnvelopedSignatureTransform();

        // Ensure the transform is using the proper algorithm.
        xmlTransform.Algorithm =
            SignedXml.XmlDsigEnvelopedSignatureTransformUrl;

        // Retrieve the XML representation of the current transform.
        XmlElement xmlInTransform = xmlTransform.GetXml();

        Console.WriteLine("\nXml representation of the current transform: ");
        Console.WriteLine(xmlInTransform.OuterXml);

        // Retrieve the valid input types for the current transform.
        Type[] validInTypes = xmlTransform.InputTypes;

        // Verify the xmlTransform can accept the XMLDocument as an
        // input type.
        for (int i=0; i<validInTypes.Length; i++)
        {
            if (validInTypes[i] == xmlDoc.GetType())
            {
                // Load the document into the transfrom.
                xmlTransform.LoadInput(xmlDoc);

                bool IncludeComments = true;
                // This transform is created for demonstration purposes.
                XmlDsigEnvelopedSignatureTransform secondTransform =
                    new XmlDsigEnvelopedSignatureTransform(IncludeComments);

                string classDescription = secondTransform.ToString();

                // This call does not perform as expected.
                // An enveloped signature has no inner XML elements
                secondTransform.LoadInnerXml(xmlDoc.SelectNodes("//."));

                break;
            }
        }

        Type[] validOutTypes = xmlTransform.OutputTypes;

        for (int i=validOutTypes.Length-1; i >= 0; i--)
        {
            if (validOutTypes[i] == typeof(System.Xml.XmlDocument))
            {
                try 
                {
                    Type xmlDocumentType = typeof(System.Xml.XmlDocument);
                    XmlDocument xmlDocumentOutput = (XmlDocument) 
                        xmlTransform.GetOutput(xmlDocumentType);

                    // Display to the console the Xml before and after
                    // encryption.
                    Console.WriteLine("Result of the GetOutput method call" +
                        " from the current transform: " + 
                        xmlDocumentOutput.OuterXml);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unexpected exception caught: " +
                        ex.ToString());
                }

                break;
            }
            else if (validOutTypes[i] == typeof(System.Xml.XmlNodeList))
            {
                try 
                {
                    Type xmlNodeListType = typeof(System.Xml.XmlNodeList);
                    XmlNodeList xmlNodes = (XmlNodeList) 
                        xmlTransform.GetOutput(xmlNodeListType);

                    // Display to the console the Xml before and after
                    // encryption.
                    Console.WriteLine("Encoding the following message: " +
                        xmlDoc.InnerText);

                    Console.WriteLine("Nodes of the XmlNodeList retrieved " +
                        "from GetOutput:");
                    for (int j=0; j < xmlNodes.Count; j++)
                    {
                        Console.WriteLine("Node " + j + 
                            " has the following name: " + 
                            xmlNodes.Item(j).Name + 
                            " and the following InnerXml: " + 
                            xmlNodes.Item(j).InnerXml);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unexpected exception caught: " +
                        ex.ToString());
                }

                break;
            }
            else
            {
                object outputObject = xmlTransform.GetOutput();
            }
        }
    }

    // Create an XML document describing various products.
    private static XmlDocument LoadProducts()
    {
        XmlDocument xmlDoc = new XmlDocument();

        string contosoProducts = "<PRODUCTS>";
        contosoProducts += "<PRODUCT><ID>123</ID>";
        contosoProducts += "<DESCRIPTION>Router</DESCRIPTION></PRODUCT>";
        contosoProducts += "<PRODUCT><ID>456</ID>";
        contosoProducts += "<DESCRIPTION>Keyboard</DESCRIPTION></PRODUCT>";
        contosoProducts += "<PRODUCT><ID>789</ID>";
        contosoProducts += "<DESCRIPTION>Monitor</DESCRIPTION></PRODUCT>";
        contosoProducts += "</PRODUCTS>";

        xmlDoc.LoadXml(contosoProducts);
        return xmlDoc;
    }

    // Create a signature and add it to the specified document.
    private static void SignDocument(ref XmlDocument xmlDoc)
    {
        // Generate a signing key.
        RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

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

        // 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.
        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

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

        try 
        {
            // Create a new KeyInfo object.
            KeyInfo keyInfo = new KeyInfo();

            // Load the X509 certificate.
            X509Certificate MSCert =
                X509Certificate.CreateFromCertFile(Certificate);

            // Load the certificate into a KeyInfoX509Data object
            // and add it to the KeyInfo object.
            keyInfo.AddClause(new KeyInfoX509Data(MSCert));

            // Add the KeyInfo object to the SignedXml object.
            signedXml.KeyInfo = keyInfo;
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine("Unable to locate the following file: " + 
                Certificate);
        }

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

        // Add the signature branch to the original tree so it is enveloped.
        xmlDoc.DocumentElement.AppendChild(signedXml.GetXml());
    }

    // Resolve the specified base and relative Uri's .
    private static Uri ResolveUris(Uri baseUri, string relativeUri)
    {
        XmlUrlResolver xmlResolver = new XmlUrlResolver();
        xmlResolver.Credentials = 
            System.Net.CredentialCache.DefaultCredentials;

        XmlDsigEnvelopedSignatureTransform xmlTransform =
            new XmlDsigEnvelopedSignatureTransform();
        xmlTransform.Resolver = xmlResolver;

        Uri absoluteUri = xmlResolver.ResolveUri(baseUri, relativeUri);

        if (absoluteUri != null)
        {
            Console.WriteLine(
                "\nResolved the base Uri and relative Uri to the following:");
            Console.WriteLine(absoluteUri.ToString());
        }
        else
        {
            Console.WriteLine(
                "Unable to resolve the base Uri and relative Uri");
        }
        return absoluteUri;
    }
}
//
// This sample produces the following output:
//
// Xml representation of the current transform: 
// <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-
// signature" xmlns="http://www.w3.org/2000/09/xmldsig#" />
// Result of the GetOutput method call from the current transform: <PRODUCTS>
// <PRODUCT><ID>123</ID><DESCRIPTION>Router</DESCRIPTION></PRODUCT><PRODUCT>
// <ID>456</ID><DESCRIPTION>Keyboard</DESCRIPTION></PRODUCT><PRODUCT><ID>789
// </ID><DESCRIPTION>Monitor</DESCRIPTION></PRODUCT></PRODUCTS>
// Unable to load the following file: ..\\my509.cer
// 
// Xml representation of the current transform: 
// <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-
// signature" xmlns="http://www.w3.org/2000/09/xmldsig#" />
// Result of the GetOutput method call from the current transform: <PRODUCTS>
// <PRODUCT><ID>123</ID><DESCRIPTION>Router</DESCRIPTION></PRODUCT><PRODUCT>
// <ID>456</ID><DESCRIPTION>Keyboard</DESCRIPTION></PRODUCT><PRODUCT><ID>789
// </ID><DESCRIPTION>Monitor</DESCRIPTION></PRODUCT><Signature xmlns=
// "http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod 
// Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
// <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
// <Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000
// /09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm=
// "http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>KvPW6HUiIUMEDS0YSoT
// gpo2JPbA=</DigestValue></Reference></SignedInfo><SignatureValue>c/njCGDru/a
// WAmWG83I+mWO040xOzxvmNx0b0o8ZyPc9j5VwApdAt103OGBtB1H6EkOvt7Ekw+PVuUo8m5LzLP
// yaTxUDMbb2kZZ5itSkGD4rmMUMUMuzrkAoquJZjxeOydBJ2CMehV2rE3RMPLIwRX176DZVy5JKU
// 6Cb7PR2Rpw=</SignatureValue></Signature></PRODUCTS>
// 
// Resolved the base Uri and relative Uri to the following:
// http://www.contoso.com/xml
// This sample completed successfully; press Enter to exit.

import System.*;
import System.IO.*;
import System.Xml.*;
import System.Security.Cryptography.*;
import System.Security.Cryptography.Xml.*;
import System.Security.Cryptography.X509Certificates.*;

class Class1
{
    private static String certificate = "..\\..\\my509.cer";

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        // Encrypt an XML message
        XmlDocument productsXml = LoadProducts();
        ShowTransformProperties(productsXml);

        SignDocument(productsXml);
        ShowTransformProperties(productsXml);
        // Use XmlDsigEnvelopedSignatureTransform to resolve a Uri.
        Uri baseUri = new Uri("http://www.contoso.com");
        String relativeUri = "xml";
        Uri absoluteUri = ResolveUris(baseUri, relativeUri);

        Console.WriteLine("This sample completed successfully; " 
            + "press Enter to exit.");
        Console.ReadLine();
    } //main

    // Encrypt the text in the specified XmlDocument.
    private static void ShowTransformProperties(XmlDocument xmlDoc)
    {
        XmlDsigEnvelopedSignatureTransform xmlTransform 
            = new XmlDsigEnvelopedSignatureTransform();

        // Ensure the transform is using the proper algorithm.
        xmlTransform.set_Algorithm(
            SignedXml.XmlDsigEnvelopedSignatureTransformUrl);

        // Retrieve the XML representation of the current transform.
        XmlElement xmlInTransform = xmlTransform.GetXml();

        Console.WriteLine("\nXml representation of the current transform: ");
        Console.WriteLine(xmlInTransform.get_OuterXml());
        // Retrieve the valid input types for the current transform.
        Type validInTypes[] = xmlTransform.get_InputTypes();

        // Verify the xmlTransform can accept the XMLDocument as an
        // input type.
        for (int i = 0; i < validInTypes.get_Length(); i++) {
            if (validInTypes.get_Item(i).Equals(xmlDoc.GetType())) {
                // Load the document into the transfrom.
                xmlTransform.LoadInput(xmlDoc);

                boolean includeComments = true;
                // This transform is created for demonstration purposes.
                XmlDsigEnvelopedSignatureTransform secondTransform 
                    = new XmlDsigEnvelopedSignatureTransform(includeComments);

                String classDescription = secondTransform.ToString();

                // This call does not perform as expected.
                // An enveloped signature has no inner XML elements
                secondTransform.LoadInnerXml(xmlDoc.SelectNodes("//."));
                break;
            }
        }
        Type validOutTypes[] = xmlTransform.get_OutputTypes();
        for (int i = validOutTypes.get_Length() - 1; i >= 0; i--) {
            if (validOutTypes.get_Item(i).Equals(System.Xml.
                XmlDocument.class.ToType())) {
                try {
                    Type xmlDocumentType = System.Xml.XmlDocument.
                        class.ToType();
                    XmlDocument xmlDocumentOutput = (XmlDocument)xmlTransform.
                        GetOutput(xmlDocumentType);

                    // Display to the console the Xml before and after
                    // encryption.
                    Console.WriteLine("Result of the GetOutput method call" 
                        + " from the current transform: " 
                        + xmlDocumentOutput.get_OuterXml());
                }
                catch (System.Exception ex) {
                    Console.WriteLine("Unexpected exception caught: " 
                        + ex.ToString());
                }
                break;
            }
            else {
                if (validOutTypes.get_Item(i).Equals(System.Xml.
                    XmlNodeList.class.ToType())) {
                    try {
                        Type xmlNodeListType = System.Xml.
                            XmlNodeList.class.ToType();
                        XmlNodeList xmlNodes = (XmlNodeList)xmlTransform.
                            GetOutput(xmlNodeListType);
                        // Display to the console the Xml before and after
                        // encryption.
                        Console.WriteLine("Encoding the following message: " 
                            + xmlDoc.get_InnerText());

                        Console.WriteLine("Nodes of the XmlNodeList retrieved " 
                            + "from GetOutput:");
                        for (int j = 0; j < xmlNodes.get_Count(); j++) {
                            Console.WriteLine("Node " + j 
                                + " has the following name: " 
                                + xmlNodes.Item(j).get_Name() 
                                + " and the following InnerXml: " 
                                + xmlNodes.Item(j).get_InnerXml());
                        }
                    }
                    catch (System.Exception ex) {
                        Console.WriteLine("Unexpected exception caught: " 
                            + ex.ToString());
                    }
                    break;
                }
                else {
                    Object outputObject = xmlTransform.GetOutput();
                } 
            }
        }
    } //ShowTransformProperties

    // Create an XML document describing various products.
    private static XmlDocument LoadProducts()
    {
        XmlDocument xmlDoc = new XmlDocument();

        String contosoProducts = "<PRODUCTS>";
        contosoProducts += "<PRODUCT><ID>123</ID>";
        contosoProducts += "<DESCRIPTION>Router</DESCRIPTION></PRODUCT>";
        contosoProducts += "<PRODUCT><ID>456</ID>";
        contosoProducts += "<DESCRIPTION>Keyboard</DESCRIPTION></PRODUCT>";
        contosoProducts += "<PRODUCT><ID>789</ID>";
        contosoProducts += "<DESCRIPTION>Monitor</DESCRIPTION></PRODUCT>";
        contosoProducts += "</PRODUCTS>";

        xmlDoc.LoadXml(contosoProducts);
        return xmlDoc;
    } //LoadProducts

    // Create a signature and add it to the specified document.
    private static void SignDocument(XmlDocument xmlDoc)
    {
        // Generate a signing key.
        RSACryptoServiceProvider key = new RSACryptoServiceProvider();
        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(xmlDoc);
        // Add the key to the SignedXml document. 
        signedXml.set_SigningKey(key);
        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.set_Uri("");
        // Add an enveloped transformation to the reference.
        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        try {
            // Create a new KeyInfo object.
            KeyInfo keyInfo = new KeyInfo();
            // Load the X509 certificate.
            X509Certificate msCert = X509Certificate.
                CreateFromCertFile(certificate);
            // Load the certificate into a KeyInfoX509Data object
            // and add it to the KeyInfo object.
            keyInfo.AddClause(new KeyInfoX509Data(msCert));
            // Add the KeyInfo object to the SignedXml object.
            signedXml.set_KeyInfo(keyInfo);
        }
        catch (FileNotFoundException ex) {
            Console.WriteLine("Unable to locate the following file: " 
                + certificate);
        }
        // Compute the signature.
        signedXml.ComputeSignature();
        // Add the signature branch to the original tree so it is enveloped.
        xmlDoc.get_DocumentElement().AppendChild(signedXml.GetXml());
    } //SignDocument

    // Resolve the specified base and relative Uri's .
    private static Uri ResolveUris(Uri baseUri, String relativeUri)
    {
        XmlUrlResolver xmlResolver = new XmlUrlResolver();
        xmlResolver.set_Credentials(System.Net.CredentialCache.
            get_DefaultCredentials());
        XmlDsigEnvelopedSignatureTransform xmlTransform 
            = new XmlDsigEnvelopedSignatureTransform();
        xmlTransform.set_Resolver(xmlResolver);

        Uri absoluteUri = xmlResolver.ResolveUri(baseUri, relativeUri);

        if (absoluteUri != null) {
            Console.WriteLine("\nResolved the base Uri and relative "
                + "Uri to the following:");
            Console.WriteLine(absoluteUri.ToString());
        }
        else {
            Console.WriteLine("Unable to resolve the base "
                + "Uri and relative Uri");
        }
        return absoluteUri;
    } //ResolveUris
} //Class1
//
// This sample produces the following output:
//
// Xml representation of the current transform: 
// <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-
// signature" xmlns="http://www.w3.org/2000/09/xmldsig#" />
// Result of the GetOutput method call from the current transform: <PRODUCTS>
// <PRODUCT><ID>123</ID><DESCRIPTION>Router</DESCRIPTION></PRODUCT><PRODUCT>
// <ID>456</ID><DESCRIPTION>Keyboard</DESCRIPTION></PRODUCT><PRODUCT><ID>789
// </ID><DESCRIPTION>Monitor</DESCRIPTION></PRODUCT></PRODUCTS>
// Unable to load the following file: ..\\my509.cer
// 
// Xml representation of the current transform: 
// <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-
// signature" xmlns="http://www.w3.org/2000/09/xmldsig#" />
// Result of the GetOutput method call from the current transform: <PRODUCTS>
// <PRODUCT><ID>123</ID><DESCRIPTION>Router</DESCRIPTION></PRODUCT><PRODUCT>
// <ID>456</ID><DESCRIPTION>Keyboard</DESCRIPTION></PRODUCT><PRODUCT><ID>789
// </ID><DESCRIPTION>Monitor</DESCRIPTION></PRODUCT><Signature xmlns=
// "http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod 
// Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
// <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
// <Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000
// /09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm=
// "http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>KvPW6HUiIUMEDS0YSoT
// gpo2JPbA=</DigestValue></Reference></SignedInfo><SignatureValue>c/njCGDru/a
// WAmWG83I+mWO040xOzxvmNx0b0o8ZyPc9j5VwApdAt103OGBtB1H6EkOvt7Ekw+PVuUo8m5LzLP
// yaTxUDMbb2kZZ5itSkGD4rmMUMUMuzrkAoquJZjxeOydBJ2CMehV2rE3RMPLIwRX176DZVy5JKU
// 6Cb7PR2Rpw=</SignatureValue></Signature></PRODUCTS>
// 
// Resolved the base Uri and relative Uri to the following:
// http://www.contoso.com/xml
// This sample completed successfully; press Enter to exit.

System.Object
   System.Security.Cryptography.Xml.Transform
    System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.