Ler em inglês

Partilhar via


XmlDsigXsltTransform Classe

Definição

Representa a transformação XSLT para uma assinatura digital, conforme definido pelo W3C.

public class XmlDsigXsltTransform : System.Security.Cryptography.Xml.Transform
Herança
XmlDsigXsltTransform

Exemplos

Esta seção contém dois exemplos de código. O primeiro exemplo de código mostra como assinar e verificar um documento XML usando a XmlDsigXsltTransform classe com uma assinatura de envelope. O segundo exemplo de código demonstra como usar membros da XmlDsigXsltTransform classe .

Exemplo nº 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)
    {
        // Generate a signing key.
        RSA Key = RSA.Create();

        string xsl = @"
    <xs:transform xmlns:xs='http://www.w3.org/1999/XSL/Transform' version='1.0'>
        <xs:template match='/'>
            <xs:apply-templates/>
        </xs:template>
        <xs:template match='ElementToTransform'>
            <transformedElement/>
        </xs:template>
    </xs:transform>";

        try
        {
            // 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, xsl);
            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);
        }
        finally
        {
            Key.Clear();
        }
    }

    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string XSLString)
    {
        // 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);

        // Create an XmlDsigXPathTransform object using
        // the helper method 'CreateXPathTransform' defined
        // later in this sample.

        XmlDsigXsltTransform XsltTransform = CreateXsltTransform(XSLString);

        // Add the transform to the reference.
        reference.AddTransform(XsltTransform);

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

        // 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 the XML that represents the transform.
    public static XmlDsigXsltTransform CreateXsltTransform(string xsl)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xsl);

        XmlDsigXsltTransform xform = new XmlDsigXsltTransform();
        xform.LoadInnerXml(doc.ChildNodes);

        return xform;
    }

    // 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, "", "MyXML", "Don't_Sign");

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

        // Create a new XmlNode object.
        XmlNode subnode = document.CreateNode(XmlNodeType.Element, "", "ElementToTransform", "Sign");

        // Add some text to the node.
        subnode.InnerText = "Here is some data to sign.";

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

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

Exemplo nº 2

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

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        XmlDocument productsXml = LoadProducts();
        XmlNodeList xsltNodeList = GetXsltAsNodeList();
        TransformDoc(productsXml, xsltNodeList);

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

    private static void TransformDoc(
        XmlDocument xmlDoc, 
        XmlNodeList xsltNodeList)
    {
        try 
        {
            // Construct a new XmlDsigXsltTransform.
            XmlDsigXsltTransform xmlTransform = 
                new XmlDsigXsltTransform();

            // Load the Xslt tranform as a node list.
            xmlTransform.LoadInnerXml(xsltNodeList);

            // Load the Xml document to perform the tranform on.
            XmlNamespaceManager namespaceManager;
            namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);

            XmlNodeList productsNodeList;
            productsNodeList = xmlDoc.SelectNodes("//.", namespaceManager);

            xmlTransform.LoadInput(productsNodeList);

            // Retrieve the output from the transform.
            Stream outputStream = (Stream)
                xmlTransform.GetOutput(typeof(System.IO.Stream));

            // Read the output stream into a stream reader.
            StreamReader streamReader =
                new StreamReader(outputStream);

            // Read the stream into a string.
            string outputMessage = streamReader.ReadToEnd();

            // Close the streams.
            outputStream.Close();
            streamReader.Close();

            // Display to the console the Xml before and after
            // encryption.
            Console.WriteLine("\nResult of transformation: " + outputMessage);
            ShowTransformProperties(xmlTransform);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught exception in TransformDoc method: " + 
                ex.ToString());
        }
    }
    
    private static XmlNodeList GetXsltAsNodeList()
    {
        string transformXml = "<xsl:transform version='1.0' ";
        transformXml += "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>";
        transformXml += "<xsl:template match='products'>";
        transformXml += "<table><tr><td>ProductId</td><td>Name</td></tr>";
        transformXml += "<xsl:apply-templates/></table></xsl:template>";
        transformXml += "<xsl:template match='product'><tr>";
        transformXml += "<xsl:apply-templates/></tr></xsl:template>";
        transformXml += "<xsl:template match='productid'><td>";
        transformXml += "<xsl:apply-templates/></td></xsl:template>";
        transformXml += "<xsl:template match='description'><td>";
        transformXml += "<xsl:apply-templates/></td></xsl:template>";
        transformXml += "</xsl:transform>";

        Console.WriteLine("\nCreated the following Xslt tranform:");
        Console.WriteLine(transformXml);

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(transformXml);
        return xmlDoc.GetElementsByTagName("xsl:transform");
    }

    // Encrypt the text in the specified XmlDocument.
    private static void ShowTransformProperties(
        XmlDsigXsltTransform xmlTransform)
    {
        string classDescription = xmlTransform.ToString();
        Console.WriteLine("\n** Summary for " + classDescription + " **");

        // Retrieve the XML representation of the current transform.
        XmlElement xmlInTransform = xmlTransform.GetXml();
        Console.WriteLine("Xml representation of the current transform:\n" +
            xmlInTransform.OuterXml);

        // Ensure the transform is using the proper algorithm.
        xmlTransform.Algorithm =
            SignedXml.XmlDsigXsltTransformUrl;
        Console.WriteLine("Algorithm used: " + classDescription);

        // Retrieve the valid input types for the current transform.
        Type[] validInTypes = xmlTransform.InputTypes;
        Console.WriteLine("Transform accepts the following inputs:");
        for (int i=0; i<validInTypes.Length; i++)
        {
            Console.WriteLine("\t" + validInTypes[i].ToString());
        }

        Type[] validOutTypes = xmlTransform.OutputTypes;
        Console.WriteLine("Transform outputs in the following types:");
        for (int i=validOutTypes.Length-1; i >= 0; i--)
        {
            Console.WriteLine("\t " + validOutTypes[i].ToString());

            if (validOutTypes[i] == typeof(object))
            {
                object outputObject = xmlTransform.GetOutput();
            }
        }
    }

    // Create an XML document describing various products.
    private static XmlDocument LoadProducts()
    {
        string contosoProducts = "<?xml version='1.0'?>";
        contosoProducts += "<products>";
        contosoProducts += "<product><productid>1</productid>";
        contosoProducts += "<description>Widgets</description></product>";
        contosoProducts += "<product><productid>2</productid>";
        contosoProducts += "<description>Gadgits</description></product>";
        contosoProducts += "</products>";

        Console.WriteLine(
            "\nCreated the following Xml document for tranformation:");
        Console.WriteLine(contosoProducts);

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(contosoProducts);
        return xmlDoc;
    }

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

        XmlDsigXsltTransform xmlTransform =
            new XmlDsigXsltTransform();
        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:
//
// Created the following Xml document for tranformation:
// <?xml version='1.0'?><products><product><productid>1</productid><descriptio
// n>Widgets</description></product><product><productid>2</productid><descript
// ion>Gadgits</description></product></products>
// 
// Created the following Xslt tranform:
// <xsl:transform version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transfor
// m'><xsl:template match='products'><table><tr><td>ProductId</td><td>Name</td
// ></tr><xsl:apply-templates/></table></xsl:template><xsl:template match='pro
// duct'><tr><xsl:apply-templates/></tr></xsl:template><xsl:emplate match='pro
// ductid'><td><xsl:apply-templates/></td></xsl:template><xsl:template match='
// description'><td><xsl:apply-templates/></td></xsl:template></xsl:transform>
// 
// Result of transformation: <table><tr><td>ProductId</td><td>Name</td></tr><t
// r><td>1</td><td>Widgets</td></tr><tr><td>2</td><td>Gadgits</td></tr></table
// >
//
// ** Summary for System.Security.Cryptography.Xml.XmlDsigXsltTransform **
// Xml representation of the current transform:
// <Transform Algorithm="http://www.w3.org/TR/1999/REC-xslt-19991116" xmlns="h
// ttp://www.w3.org/2000/09/xmldsig#"><xsl:transform version="1.0" xmlns:xsl="
// http://www.w3.org/1999/XSL/Transform"><xsl:template match="products"><table
//  xmlns=""><tr><td>ProductId</td><td>Name</td></tr><xsl:apply-templates /></
// table></xsl:template><xsl:template match="product"><tr xmlns=""><xsl:apply-
// templates /></tr></xsl:template><xsl:template match="productid"><td xmlns="
// "><xsl:apply-templates /></td></xsl:template><xsl:template match="descripti
// on"><td xmlns=""><xsl:apply-templates /></td></xsl:template></xsl:transform
// ></Transform>
// Algorithm used: System.Security.Cryptography.Xml.XmlDsigXsltTransform
// Transform accepts the following inputs:
// System.IO.Stream
// System.Xml.XmlDocument
// System.Xml.XmlNodeList
// Transform outputs in the following types:
// System.IO.Stream
// 
// Resolved the base Uri and relative Uri to the following:
// http://www.contoso.com/xml
// This sample completed successfully; press Enter to exit.

Comentários

A XmlDsigXPathTransform classe permite que você resolva um documento XML usando uma transformação XSLT. Essa classe usa XSLT para transformar nós XML em outros nós XML que você deseja assinar ou criptografar.

Use a XmlDsigXsltTransform classe para assinar ou criptografar partes específicas de um documento XML usando uma transformação XSLT.

O URI (Uniform Resource Identifier) que descreve a XmlDsigXsltTransform classe é definido pelo XmlDsigXsltTransformUrl campo .

Para obter mais informações sobre a transformação XSLT, consulte Seção 6.6.5 da especificação XMLDSIG do W3C.

Construtores

XmlDsigXsltTransform()

Inicializa uma nova instância da classe XmlDsigXsltTransform.

XmlDsigXsltTransform(Boolean)

Inicializa uma nova instância da classe XmlDsigXsltTransform com comentários, se especificado.

Propriedades

Algorithm

Obtém ou define o URI (Uniform Resource Identifier) que identifica o algoritmo executado pela transformação atual.

(Herdado de Transform)
Context

Obtém ou define um objeto XmlElement que representa o contexto do documento em que o objeto Transform atual está em execução.

(Herdado de Transform)
InputTypes

Obtém uma matriz de tipos que são entradas válidas para o método LoadInput(Object) do objeto XmlDsigXsltTransform atual.

OutputTypes

Obtém uma matriz de tipos que são possíveis saídas provenientes de métodos GetOutput() do objeto XmlDsigXsltTransform atual.

PropagatedNamespaces

Obtém ou define um objeto Hashtable que contém os namespaces propagados na assinatura.

(Herdado de Transform)
Resolver

Define o objeto XmlResolver atual.

(Herdado de Transform)

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetDigestedOutput(HashAlgorithm)

Quando substituído em uma classe derivada, retorna o resumo da mensagem associado a um objeto Transform.

(Herdado de Transform)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetInnerXml()

Retorna uma representação XML dos parâmetros do objeto XmlDsigXsltTransform adequados para serem incluídos como subelementos de um elemento <Transform> XMLDSIG.

GetOutput()

Retorna a saída do objeto XmlDsigXsltTransform atual.

GetOutput(Type)

Retorna a saída do objeto XmlDsigXsltTransform atual do tipo Stream.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
GetXml()

Retorna a representação XML do objeto Transform atual.

(Herdado de Transform)
LoadInnerXml(XmlNodeList)

Analisa o objeto XmlNodeList especificado como conteúdo específico da transformação de um elemento <Transform> e configura o estado interno do objeto XmlDsigXsltTransform atual para corresponder ao elemento <Transform>.

LoadInput(Object)

Carrega a entrada especificada no objeto XmlDsigXsltTransform atual.

MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a