Lire en anglais

Partager via


XmlDsigC14NWithCommentsTransform Classe

Définition

Représente la transformation, avec commentaires, selon les spécifications de canonisation (C14N) XML d'une signature numérique définies par le W3C (World Wide Web Consortium).

C#
public class XmlDsigC14NWithCommentsTransform : System.Security.Cryptography.Xml.XmlDsigC14NTransform
Héritage
XmlDsigC14NWithCommentsTransform

Exemples

Cette section contient deux exemples de code. Le premier exemple montre comment signer un fichier XML à l’aide d’une signature détachée. Cet exemple crée une signature de www.microsoft.com dans un fichier XML, puis vérifie le fichier. Le deuxième exemple montre comment signer un fichier XML à l’aide d’une signature d’enveloppe. Cet exemple crée une signature d’un fichier XML, puis enregistre la signature dans un nouveau fichier XML.

Exemple n°1

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

Exemple n°2

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

Remarques

La XmlDsigC14NWithCommentsTransform classe représente la transformation de canonisation XML C14N qui décrit la forme canonique d’un document XML. Cette transformation permet à un signataire de créer un condensé à l’aide de la forme canonique d’un document XML. Un destinataire peut ensuite vérifier la signature numérique à l’aide de la même forme canonique du document XML avec la même transformation.

Utilisez la XmlDsigC14NWithCommentsTransform classe lorsque vous devez signer un document XML qui contient des commentaires.

Notez que vous ne pouvez pas créer directement une nouvelle instance d’une classe de transformation de canonisation. Pour spécifier une transformation de canonisation, transmettez l’URI (Uniform Resource Identifier) qui décrit la transformation à la CanonicalizationMethod propriété, qui est accessible à partir de la SignedInfo propriété . Pour acquérir une référence à la transformation de canonisation, utilisez la CanonicalizationMethodObject propriété , qui est accessible à partir de la SignedInfo propriété .

L’URI qui décrit la XmlDsigExcC14NWithCommentsTransform classe est défini par le XmlDsigExcC14NWithCommentsTransformUrl champ .

L’URI qui décrit la XmlDsigC14NWithCommentsTransform classe est défini par le XmlDsigC14NWithCommentsTransformUrl champ et le XmlDsigCanonicalizationWithCommentsUrl champ .

Pour plus d’informations sur la transformation C14N avec commentaires, consultez les sections 6.5 et 6.6.1 de la spécification XMLDSIG du W3C. L’algorithme de canonisation est défini dans la spécification XML canonique du W3C.

Constructeurs

XmlDsigC14NWithCommentsTransform()

Initialise une nouvelle instance de la classe XmlDsigC14NWithCommentsTransform.

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 XmlDsigC14NTransform en cours.

(Hérité de XmlDsigC14NTransform)
OutputTypes

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

(Hérité de XmlDsigC14NTransform)
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)

Retourne le Digest associé à un objet XmlDsigC14NTransform.

(Hérité de XmlDsigC14NTransform)
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 XmlDsigC14NTransform qui conviennent pour être inclus comme sous-éléments d'un élément <Transform> XMLDSIG.

(Hérité de XmlDsigC14NTransform)
GetOutput()

Retourne la sortie de l'objet XmlDsigC14NTransform en cours.

(Hérité de XmlDsigC14NTransform)
GetOutput(Type)

Retourne la sortie de l'objet XmlDsigC14NTransform en cours, de type Stream.

(Hérité de XmlDsigC14NTransform)
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 l'objet XmlNodeList spécifié en tant que contenu spécifique à la transformation d'un élément <Transform> ; cette méthode n'est pas prise en charge car cet élément ne possède pas d'éléments XML internes.

(Hérité de XmlDsigC14NTransform)
LoadInput(Object)

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

(Hérité de XmlDsigC14NTransform)
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 8 (package-provided), 9 (package-provided), 10 (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, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10