XmlDsigC14NWithCommentsTransform Klasa

Definicja

Reprezentuje transformację kanoniczną XML C14N dla podpisu cyfrowego zdefiniowanego przez World Wide Web Consortium (W3C) z komentarzami.

C#
public class XmlDsigC14NWithCommentsTransform : System.Security.Cryptography.Xml.XmlDsigC14NTransform
Dziedziczenie
XmlDsigC14NWithCommentsTransform

Przykłady

Ten rozdział zawiera dwa przykłady kodu. W pierwszym przykładzie pokazano, jak podpisać plik XML przy użyciu odłączonego podpisu. W tym przykładzie zostanie utworzony podpis www.microsoft.com w pliku XML, a następnie zweryfikuje plik. W drugim przykładzie pokazano, jak podpisać plik XML przy użyciu podpisu koperty. W tym przykładzie zostanie utworzony podpis pliku XML, a następnie zapisze podpis w nowym pliku XML.

Przykład nr 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();
    }
}

Przykład nr 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();
    }
}

Uwagi

Klasa XmlDsigC14NWithCommentsTransform reprezentuje transformację kanoniczną XML C14N, która opisuje kanoniczną formę dokumentu XML. Ta transformacja umożliwia znakatorowi utworzenie skrótu przy użyciu kanonicznej formy dokumentu XML. Odbiorca może następnie zweryfikować podpis cyfrowy przy użyciu tej samej formy kanonicznej dokumentu XML z tą samą transformacją.

Użyj klasy , XmlDsigC14NWithCommentsTransform gdy musisz podpisać dokument XML zawierający komentarze.

Należy pamiętać, że nie można bezpośrednio utworzyć nowego wystąpienia klasy transformacji kanonicznej. Aby określić przekształcenie kanoniczne, przekaż identyfikator URI (Uniform Resource Identifier), który opisuje przekształcenie do CanonicalizationMethod właściwości, która jest dostępna z SignedInfo właściwości. Aby uzyskać odwołanie do przekształcenia kanonicznego, użyj CanonicalizationMethodObject właściwości , która jest dostępna z SignedInfo właściwości .

Identyfikator URI opisujący klasę XmlDsigExcC14NWithCommentsTransformXmlDsigExcC14NWithCommentsTransformUrl jest definiowany przez pole.

Identyfikator URI opisujący klasę XmlDsigC14NWithCommentsTransform jest definiowany przez XmlDsigC14NWithCommentsTransformUrl pole i XmlDsigCanonicalizationWithCommentsUrl pole.

Aby uzyskać więcej informacji na temat przekształcenia C14N z komentarzami, zobacz Sekcje 6.5 i 6.6.1 specyfikacji W3C XMLDSIG. Algorytm canonicalization jest zdefiniowany w specyfikacji W3C Canonical XML.

Konstruktory

Właściwości

Algorithm

Pobiera lub ustawia identyfikator URI (Uniform Resource Identifier), który identyfikuje algorytm wykonywany przez bieżącą transformację.

(Odziedziczone po Transform)
Context

Pobiera lub ustawia XmlElement obiekt reprezentujący kontekst dokumentu, w którym jest uruchomiony bieżący Transform obiekt.

(Odziedziczone po Transform)
InputTypes

Pobiera tablicę typów, które są prawidłowymi danymi wejściowymi metody LoadInput(Object) bieżącego XmlDsigC14NTransform obiektu.

(Odziedziczone po XmlDsigC14NTransform)
OutputTypes

Pobiera tablicę typów, które są możliwymi danymi wyjściowymi z GetOutput() metod bieżącego XmlDsigC14NTransform obiektu.

(Odziedziczone po XmlDsigC14NTransform)
PropagatedNamespaces

Pobiera lub ustawia Hashtable obiekt zawierający przestrzenie nazw, które są propagowane do podpisu.

(Odziedziczone po Transform)
Resolver

Ustawia bieżący XmlResolver obiekt.

(Odziedziczone po Transform)

Metody

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetDigestedOutput(HashAlgorithm)

Zwraca skrót skojarzony z obiektem XmlDsigC14NTransform .

(Odziedziczone po XmlDsigC14NTransform)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetInnerXml()

Zwraca reprezentację XML parametrów XmlDsigC14NTransform obiektu, który jest odpowiedni do dołączenia jako podelementy elementu XMLDSIG <Transform> .

(Odziedziczone po XmlDsigC14NTransform)
GetOutput()

Zwraca dane wyjściowe bieżącego XmlDsigC14NTransform obiektu.

(Odziedziczone po XmlDsigC14NTransform)
GetOutput(Type)

Zwraca dane wyjściowe bieżącego XmlDsigC14NTransform obiektu typu Stream.

(Odziedziczone po XmlDsigC14NTransform)
GetType()

Type Pobiera bieżące wystąpienie.

(Odziedziczone po Object)
GetXml()

Zwraca reprezentację XML bieżącego Transform obiektu.

(Odziedziczone po Transform)
LoadInnerXml(XmlNodeList)

Analizuje określony XmlNodeList obiekt jako zawartość specyficzną <Transform> dla transformacji elementu. Ta metoda nie jest obsługiwana, ponieważ ten element nie ma wewnętrznych elementów XML.

(Odziedziczone po XmlDsigC14NTransform)
LoadInput(Object)

Ładuje określone dane wejściowe do bieżącego XmlDsigC14NTransform obiektu.

(Odziedziczone po XmlDsigC14NTransform)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Dotyczy

Produkt Wersje
.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