Lire en anglais

Partager via


XmlDsigEnvelopedSignatureTransform Classe

Définition

Représente la transformation de signature enveloppée pour une signature numérique XML, conformément à la définition du W3C (World Wide Web Consortium).

C#
public class XmlDsigEnvelopedSignatureTransform : System.Security.Cryptography.Xml.Transform
Héritage
XmlDsigEnvelopedSignatureTransform

Exemples

Cette section contient deux exemples de code. Le premier exemple montre comment signer un fichier XML à l’aide d’une signature d’enveloppe. Le deuxième exemple montre comment utiliser des membres de la XmlDsigEnvelopedSignatureTransform classe.

Exemple #1

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

Exemple #2

C#
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.
        RSA Key = RSA.Create();

        // 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.

Remarques

La XmlDsigEnvelopedSignatureTransform classe supprime l’élément <Signature> d’un document XML avant le calcul de la synthèse. Avec cette transformation, vous pouvez signer et vérifier tous les éléments d’un document XML à l’exception des éléments de signature numérique XML.

Bien que vous puissiez créer et insérer une signature dans un document XML, la vérification du document modifié à l’aide de la signature incorporée échoue, car le document possède désormais des éléments supplémentaires. Cette transformation supprime l’élément et vous permet de vérifier le <Signature> document à l’aide de son formulaire d’origine.

Utilisez la XmlDsigEnvelopedSignatureTransform classe chaque fois que vous créez une signature enveloppe.

Pour plus d’informations sur la transformation de signature enveloppe, consultez la section 6.6.4 de la spécification W3C XMLDSIG.

Constructeurs

XmlDsigEnvelopedSignatureTransform()

Initialise une nouvelle instance de la classe XmlDsigEnvelopedSignatureTransform.

XmlDsigEnvelopedSignatureTransform(Boolean)

Initialise une nouvelle instance de la classe XmlDsigEnvelopedSignatureTransform avec des commentaires (s'ils sont spécifiés).

Propriétés

Algorithm

Obtient ou définit l'URI (Uniform Resource Identifier) qui identifie l'algorithme exécuté par la transformation actuelle.

(Hérité de Transform)
Context

Obtient ou définit un objet XmlElement qui représente le contexte de document dans lequel l'objet Transform actuel est exécuté.

(Hérité de Transform)
InputTypes

Obtient un tableau de types qui constituent des entrées valides dans les méthodes LoadInput(Object) de l'objet XmlDsigEnvelopedSignatureTransform en cours.

OutputTypes

Obtient un tableau de types qui constituent des sorties valides des méthodes GetOutput() de l'objet XmlDsigEnvelopedSignatureTransform en cours.

PropagatedNamespaces

Obtient ou définit un objet Hashtable qui contient les espaces de noms qui sont propagés dans la signature.

(Hérité de Transform)
Resolver

Définit l'objet XmlResolver en cours.

(Hérité de Transform)

Méthodes

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.

(Hérité de Object)
GetDigestedOutput(HashAlgorithm)

En cas de substitution dans une classe dérivée, retourne le Digest associé à un objet Transform.

(Hérité de Transform)
GetHashCode()

Fait office de fonction de hachage par défaut.

(Hérité de Object)
GetInnerXml()

Retourne une représentation XML des paramètres d'un objet XmlDsigEnvelopedSignatureTransform qui conviennent pour être inclus comme sous-éléments d'un élément <Transform> XMLDSIG.

GetOutput()

Retourne la sortie de l'objet XmlDsigEnvelopedSignatureTransform en cours.

GetOutput(Type)

Retourne la sortie de l'objet XmlDsigEnvelopedSignatureTransform en cours, de type XmlNodeList.

GetType()

Obtient le Type de l'instance actuelle.

(Hérité de Object)
GetXml()

Retourne la représentation XML de l'objet Transform en cours.

(Hérité de Transform)
LoadInnerXml(XmlNodeList)

Analyse le XmlNodeList spécifié en tant que contenu propre à la transformation d'un élément <Transform> et configure l'état interne de l'objet XmlDsigEnvelopedSignatureTransform en cours en fonction de l'élément <Transform>.

LoadInput(Object)

Charge l'entrée spécifiée dans l'objet XmlDsigEnvelopedSignatureTransform en cours.

MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
ToString()

Retourne une chaîne qui représente l'objet actuel.

(Hérité de Object)

S’applique à

Produit Versions
.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, 4.7.1, 4.7.2, 4.8
Windows Desktop 3.0, 3.1, 5, 6, 7