XmlDsigXsltTransformとは? わかりやすく解説

XmlDsigXsltTransform クラス

W3C によって定義された、デジタル署名XSLT 変換表します

名前空間: System.Security.Cryptography.Xml
アセンブリ: System.Security (system.security.dll 内)
構文構文

Public Class XmlDsigXsltTransform
    Inherits Transform
Dim instance As XmlDsigXsltTransform
public class XmlDsigXsltTransform : Transform
public ref class XmlDsigXsltTransform : public
 Transform
public class XmlDsigXsltTransform extends Transform
public class XmlDsigXsltTransform extends
 Transform
解説解説

XmlDsigXPathTransform クラス使用すると、XSLT 変換使用して XML ドキュメント操作できます。このクラスは、XSLT使用してXML ノード署名または暗号化する 他の XML ノード変換します

XML ドキュメント特定の部分XSLT 変換選択して署名または暗号化するには、XmlDsigXsltTransform クラス使用します

XmlDsigXsltTransform クラス記述する URI (Uniform Resource Identifier) は、XmlDsigXsltTransformUrl フィールドによって定義されます。

XSLT 変換詳細については、W3C (www.w3.org/TR/xmldsig-core/) から提供されている XMLDSIG 仕様セクション 6.6.5 を参照してください

使用例使用例

このセクションには、2 つコード例含まれています。1 つ目のコードには、エンベロープ シグネチャXmlDsigXsltTransform クラス使用しXML ドキュメント署名および検証を行う例が示されています。2 番目のコード例は、XmlDsigXsltTransform クラスメンバ使用する方法示してます。

例 1

'
' This example signs an XML file using an
' envelope signature. It then verifies the 
' signed XML.
'
Imports System
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.Xml
Imports System.Text
Imports System.Xml



Module SignVerifyEnvelope


    Sub Main(ByVal args() As
 String)
        ' Generate a signing key.
        Dim Key As New RSACryptoServiceProvider()

        Dim xsl As String
 = "<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...")
            Dim result As Boolean
 = VerifyXmlFile("SignedExample.xml")

            ' Display the results of the signature verification to \
            ' the console.
            If result Then
                Console.WriteLine("The XML signature is valid.")
            Else
                Console.WriteLine("The XML signature is not valid.")
            End If
        Catch e As CryptographicException
            Console.WriteLine(e.Message)
        Finally
            Key.Clear()
        End Try

    End Sub


    ' Sign an XML file and save the signature in a new file.
    Sub SignXmlFile(ByVal FileName As
 String, ByVal SignedFileName As
 String, ByVal Key As RSA, ByVal XSLString As String)
        ' Create a new XML document.
        Dim doc As 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.
        Dim signedXml As New
 SignedXml(doc)

        ' Add the key to the SignedXml document. 
        signedXml.SigningKey = Key

        ' Create a reference to be signed.
        Dim reference As New
 Reference()
        reference.Uri = ""

        ' Add an enveloped transformation to the reference.
        Dim env As New XmlDsigEnvelopedSignatureTransform()
        reference.AddTransform(env)

        ' Create an XmlDsigXPathTransform object using 
        ' the helper method 'CreateXPathTransform' defined
        ' later in this sample.
        Dim XsltTransform As XmlDsigXsltTransform
 = 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).
        Dim keyInfo As New
 KeyInfo()
        keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA)))
        signedXml.KeyInfo = keyInfo

        ' Compute the signature.
        signedXml.ComputeSignature()

        ' Get the XML representation of the signature and save
        ' it to an XmlElement object.
        Dim xmlDigitalSignature As XmlElement
 = 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.
        Dim xmltw As New
 XmlTextWriter(SignedFileName, New UTF8Encoding(False))
        doc.WriteTo(xmltw)
        xmltw.Close()

    End Sub

    ' Verify the signature of an XML file and return the result.
    Function VerifyXmlFile(ByVal Name As
 String) As [Boolean]
        ' Create a new XML document.
        Dim xmlDocument As 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.
        Dim signedXml As New
 SignedXml(xmlDocument)

        ' Find the "Signature" node and create a new
        ' XmlNodeList object.
        Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature")

        ' Load the signature node.
        signedXml.LoadXml(CType(nodeList(0), XmlElement))

        ' Check the signature and return the result.
        Return signedXml.CheckSignature()

    End Function


    ' Create the XML that represents the transform.
    Function CreateXsltTransform(ByVal xsl
 As String) As XmlDsigXsltTransform
        Dim doc As New XmlDocument()
        doc.LoadXml(xsl)

        Dim xform As New
 XmlDsigXsltTransform()
        xform.LoadInnerXml(doc.ChildNodes)

        Return xform

    End Function


    ' Create example data to sign.
    Sub CreateSomeXml(ByVal FileName As
 String)
        ' Create a new XmlDocument object.
        Dim document As New
 XmlDocument()

        ' Create a new XmlNode object.
        Dim node As XmlNode = document.CreateNode(XmlNodeType.Element,
 "", "MyXML", "Don't_Sign")

        ' Append the node to the document.
        document.AppendChild(node)

        ' Create a new XmlNode object.
        Dim subnode As XmlNode = 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.
        Dim xmltw As New
 XmlTextWriter(FileName, New UTF8Encoding(False))
        document.WriteTo(xmltw)
        xmltw.Close()

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

        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();
    }
}
//
// This example signs an XML file using an
// envelope signature. It then verifies the 
// signed XML.
//
#using <System.Xml.dll>
#using <System.Security.dll>
#using <System.dll>

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::Security::Cryptography::Xml;
using namespace System::Text;
using namespace System::Xml;

// Create the XML that represents the transform.
static XmlDsigXsltTransform^ CreateXsltTransform( String^ xsl
 )
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( xsl );
   XmlDsigXsltTransform^ xform = gcnew XmlDsigXsltTransform;
   xform->LoadInnerXml( doc->ChildNodes );
   return xform;
}


// Sign an XML file and save the signature in a new file.
static void SignXmlFile( String^ FileName,
 String^ SignedFileName, RSA^ Key, String^ XSLString )
{
   
   // Create a new XML document.
   XmlDocument^ doc = gcnew XmlDocument;
   
   // Format the document to ignore white spaces.
   doc->PreserveWhitespace = false;
   
   // Load the passed XML file using it's name.
   doc->Load( gcnew XmlTextReader( FileName ) );
   
   // Create a SignedXml object.
   SignedXml^ signedXml = gcnew SignedXml( doc );
   
   // Add the key to the SignedXml document. 
   signedXml->SigningKey = Key;
   
   // Create a reference to be signed.
   Reference^ reference = gcnew Reference;
   reference->Uri = L"";
   
   // Add an enveloped transformation to the reference.
   XmlDsigEnvelopedSignatureTransform^ env = gcnew 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 = gcnew KeyInfo;
   keyInfo->AddClause( gcnew RSAKeyValue( dynamic_cast<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 = gcnew XmlTextWriter( SignedFileName,gcnew UTF8Encoding(
 false ) );
   doc->WriteTo( xmltw );
   xmltw->Close();
}


// Verify the signature of an XML file and return the result.
static Boolean VerifyXmlFile( String^ Name )
{
   
   // Create a new XML document.
   XmlDocument^ xmlDocument = gcnew 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 = gcnew SignedXml( xmlDocument );
   
   // Find the "Signature" node and create a new
   // XmlNodeList object.
   XmlNodeList^ nodeList = xmlDocument->GetElementsByTagName( L"Signature"
 );
   
   // Load the signature node.
   signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList->Item( 0 ))
 );
   
   // Check the signature and return the result.
   return signedXml->CheckSignature();
}


// Create example data to sign.
static void CreateSomeXml( String^ FileName
 )
{
   
   // Create a new XmlDocument object.
   XmlDocument^ document = gcnew XmlDocument;
   
   // Create a new XmlNode object.
   XmlNode^ node = document->CreateNode( XmlNodeType::Element, L"",
 L"MyXML", L"Don't_Sign" );
   
   // Append the node to the document.
   document->AppendChild( node );
   
   // Create a new XmlNode object.
   XmlNode^ subnode = document->CreateNode( XmlNodeType::Element, L"",
 L"ElementToTransform", L"Sign" );
   
   // Add some text to the node.
   subnode->InnerText = L"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 = gcnew XmlTextWriter( FileName,gcnew UTF8Encoding( false
 ) );
   document->WriteTo( xmltw );
   xmltw->Close();
}

int main()
{
   
   // Generate a signing key.
   RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider;
   String^ xsl = L"\r\n    <xs:transform xmlns:xs='http://www.w3.org/1999/XSL/Transform'
 version='1.0'>\r\n        <xs:template match='/'>\r\n            <xs:apply-templates/>\r\n
        </xs:template>\r\n        <xs:template match='ElementToTransform'> \r\n            <transformedElement/>\r\n        </xs:template>\r\n    </xs:transform>";
   try
   {
      
      // Create an XML file to sign.
      CreateSomeXml( L"Example.xml" );
      Console::WriteLine( L"New XML file created." );
      
      // Sign the XML that was just created and save it in a 
      // new file.
      SignXmlFile( L"Example.xml", L"SignedExample.xml", Key,
 xsl );
      Console::WriteLine( L"XML file signed." );
      
      // Verify the signature of the signed XML.
      Console::WriteLine( L"Verifying signature..." );
      bool result = VerifyXmlFile( L"SignedExample.xml"
 );
      
      // Display the results of the signature verification to \
      // the console.
      if ( result )
      {
         Console::WriteLine( L"The XML signature is valid." );
      }
      else
      {
         Console::WriteLine( L"The XML signature is not valid." );
      }
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( e->Message );
   }
   finally
   {
      Key->Clear();
   }

   return 1;
}

例 2

Imports System
Imports System.IO
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Text

Public Class Form1
    Inherits System.Windows.Forms.Form

    ' Event handler for Run button.
    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles
 Button1.Click

        tbxOutput.Cursor = Cursors.WaitCursor
        tbxOutput.Text = ""

        Dim productsXml As XmlDocument = LoadProducts()
        Dim xsltNodeList As XmlNodeList = GetXsltAsNodeList()
        TransformDoc(productsXml, xsltNodeList)

        ' Use XmlDsigXsltTransform to resolve a Uri.
        Dim baseUri As New
 Uri("http://www.contoso.com")
        Dim relativeUri As String
 = "xml"
        Dim absoluteUri As Uri = ResolveUris(baseUri,
 relativeUri)

        ' Align interface and conclude application.
        WriteLine(vbCrLf + "This sample completed successfully;"
 + _
            " press Exit to continue.")

        ' Reset the cursor.
        tbxOutput.Cursor = Cursors.Default
    End Sub

    ' Create an XML document describing various products.
    Private Function LoadProducts() As
 XmlDocument
        Dim contosoProducts As String
 = "<?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>"

        WriteLine(vbCrLf + _
            "Created the following Xml document for tranformation:")
        WriteLine(contosoProducts)

        Dim xmlDoc As New
 XmlDocument
        xmlDoc.LoadXml(contosoProducts)
        Return xmlDoc
    End Function

    Private Function GetXsltAsNodeList() As
 XmlNodeList
        Dim transformXml As String
 = "<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>"

        WriteLine(vbCrLf + "Created the following Xslt tranform:")
        WriteLine(transformXml)

        Dim xmlDoc As New
 XmlDocument
        xmlDoc.LoadXml(transformXml)
        Return xmlDoc.GetElementsByTagName("xsl:transform")
    End Function

    Private Sub TransformDoc( _
        ByVal xmlDoc As XmlDocument, _
        ByVal xsltNodeList As XmlNodeList)

        Try
            ' Construct a new XmlDsigXsltTransform.
            Dim xmlTransform As New
 XmlDsigXsltTransform

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

            ' Load the Xml document to perform the tranform on.
            dim namespaceManager as New
 XmlNamespaceManager(xmlDoc.NameTable)

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

            xmlTransform.LoadInput(productsNodeList)

            ' Retrieve the output from the transform.
            Dim outputStream As Stream
            outputStream = CType(xmlTransform.GetOutput( _
                GetType(System.IO.Stream)), _
                System.IO.Stream)

            ' Read the output stream into a stream reader.
            Dim streamReader As New
 StreamReader(outputStream)

            ' Read the stream into a string.
            Dim outputMessage As String
 = streamReader.ReadToEnd()

            ' Close the streams.
            outputStream.Close()
            streamReader.Close()

            ' Display to the console the Xml before and after encryption.
            WriteLine(vbCrLf + "Result of transformation: "
 + outputMessage)
            ShowTransformProperties(xmlTransform)
        Catch ex As Exception
            WriteLine("Caught exception in TransformDoc method:
 " + _
                ex.ToString())
        End Try
    End Sub

    Private Sub ShowTransformProperties( _
            ByVal xmlTransform As XmlDsigXsltTransform)

        Dim classDescription As String
 = xmlTransform.ToString()
        WriteLine(vbCrLf + "** Summary for " + classDescription
 + " **")

        ' Retrieve the XML representation of the current transform.
        Dim xmlInTransform As XmlElement =
 xmlTransform.GetXml()
        WriteLine("Xml representation of the current transform:"
 + _
            vbCrLf + 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.
        Dim validInTypes() As Type = xmlTransform.InputTypes
        WriteLine("Transform accepts the following inputs:")
        For i As Int16 = 0 To
 validInTypes.Length - 1 Step 1
            WriteLine("   " + validInTypes(i).ToString())
        Next

        Dim validOutTypes() As Type = xmlTransform.OutputTypes
        WriteLine("Transform outputs in the following types:")
        For j As Int16 = 0 To
 validOutTypes.Length - 1 Step 1

            WriteLine("   " + validOutTypes(j).ToString())
            If (validOutTypes(j).Equals(GetType(Object)))
 Then
                Dim outputObject As Object
 = xmlTransform.GetOutput()
            End If
        Next
    End Sub

    ' Resolve the specified base and relative Uri's .
    Private Function ResolveUris( _
        ByVal baseUri As Uri, _
        ByVal relativeUri As String)
 As Uri

        Dim xmlResolver As New
 XmlUrlResolver
        xmlResolver.Credentials = _
            System.Net.CredentialCache.DefaultCredentials

        Dim xmlTransform As New
 XmlDsigXsltTransform
        xmlTransform.Resolver = xmlResolver

        Dim absoluteUri As Uri = xmlResolver.ResolveUri(baseUri,
 relativeUri)
        If (Not absoluteUri Is
 Nothing) Then
            WriteLine(vbCrLf + _
                "Resolved the base Uri and relative Uri to the
 following:")
            WriteLine(absoluteUri.ToString())
        Else
            WriteLine("Unable to resolve the base Uri and relative
 Uri")
        End If
        
        Return absoluteUri
    End Function

    ' Write specified message and carriage return to the output textbox.
    Private Sub WriteLine(ByVal
 message As String)
        tbxOutput.AppendText(message + vbCrLf)

    End Sub

    ' Event handler for Exit button.
    Private Sub Button2_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles
 Button2.Click

        Application.Exit()
    End Sub
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides
 Sub Dispose(ByVal disposing As
 Boolean)
        If disposing Then
            If Not (components Is
 Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents Panel2 As
 System.Windows.Forms.Panel
    Friend WithEvents Panel1 As
 System.Windows.Forms.Panel
    Friend WithEvents Button1 As
 System.Windows.Forms.Button
    Friend WithEvents Button2 As
 System.Windows.Forms.Button
    Friend WithEvents tbxOutput As
 System.Windows.Forms.RichTextBox
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Panel2 = New System.Windows.Forms.Panel
        Me.Button1 = New System.Windows.Forms.Button
        Me.Button2 = New System.Windows.Forms.Button
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.tbxOutput = New System.Windows.Forms.RichTextBox
        Me.Panel2.SuspendLayout()
        Me.Panel1.SuspendLayout()
        Me.SuspendLayout()
        '
        'Panel2
        '
        Me.Panel2.Controls.Add(Me.Button1)
        Me.Panel2.Controls.Add(Me.Button2)
        Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
        Me.Panel2.DockPadding.All = 20
        Me.Panel2.Location = New System.Drawing.Point(0,
 320)
        Me.Panel2.Name = "Panel2"
        Me.Panel2.Size = New System.Drawing.Size(616,
 64)
        Me.Panel2.TabIndex = 1
        '
        'Button1
        '
        Me.Button1.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button1.Font = New System.Drawing.Font(
 _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button1.Location = New System.Drawing.Point(446,
 20)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(75,
 24)
        Me.Button1.TabIndex = 2
        Me.Button1.Text = "&Run"
        '
        'Button2
        '
        Me.Button2.Dock = System.Windows.Forms.DockStyle.Right
        Me.Button2.Font = New System.Drawing.Font(
 _
            "Microsoft Sans Serif", _
            9.0!, _
            System.Drawing.FontStyle.Regular, _
            System.Drawing.GraphicsUnit.Point, _
            CType(0, Byte))
        Me.Button2.Location = New System.Drawing.Point(521,
 20)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(75,
 24)
        Me.Button2.TabIndex = 3
        Me.Button2.Text = "E&xit"
        '
        'Panel1
        '
        Me.Panel1.Controls.Add(Me.tbxOutput)
        Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.Panel1.DockPadding.All = 20
        Me.Panel1.Location = New System.Drawing.Point(0,
 0)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(616,
 320)
        Me.Panel1.TabIndex = 2
        '
        'tbxOutput
        '
        Me.tbxOutput.AccessibleDescription = _
            "Displays output from application."
        Me.tbxOutput.AccessibleName = "Output
 textbox."
        Me.tbxOutput.Dock = System.Windows.Forms.DockStyle.Fill
        Me.tbxOutput.Location = New System.Drawing.Point(20,
 20)
        Me.tbxOutput.Name = "tbxOutput"
        Me.tbxOutput.Size = New System.Drawing.Size(576,
 280)
        Me.tbxOutput.TabIndex = 1
        Me.tbxOutput.Text = "Click the Run
 button to run the application."
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(6,
 15)
        Me.ClientSize = New System.Drawing.Size(616,
 384)
        Me.Controls.Add(Me.Panel1)
        Me.Controls.Add(Me.Panel2)
        Me.Name = "Form1"
        Me.Text = "XmlDsigXsltTransform"
        Me.Panel2.ResumeLayout(False)
        Me.Panel1.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region
End Class
'
' This sample produces the following output:
' 
' Created the following Xml document for tranformation:
' <?xml version='1.0'?><products><product><productid>1</productid><description
' >Widgets</description></product><product><productid>2</productid><descriptio
' n>Gadgits</description></product></products>
' 
' Created the following Xslt tranform:
' <xsl:transform version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform
' '><xsl:template match='products'><table><tr><td>ProductId</td><td>Name</td><
' /tr><xsl:apply-templates/></table></xsl:template><xsl:template
 match='produc
' t'><tr><xsl:apply-templates/></tr></xsl:template><xsl:template
 match='produc
' tid'><td><xsl:apply-templates/></td></xsl:template><xsl:template
 match='desc
' ription'><td><xsl:apply-templates/></td></xsl:template></xsl:transform>
' 
' Result of transformation: <table><tr><td>ProductId</td><td>Name</td></tr><tr
' ><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="ht
' tp://www.w3.org/2000/09/xmldsig#"><xsl:transform version="1.0"
 xmlns:xsl="ht
' tp://www.w3.org/1999/XSL/Transform"><xsl:template match="products"><table
 xm
' lns=""><tr><td>ProductId</td><td>Name</td></tr><xsl:apply-templates
 /></tabl
' e></xsl:template><xsl:template match="product"><tr
 xmlns=""><xsl:apply-templ
' ates /></tr></xsl:template><xsl:template match="productid"><td
 xmlns=""><xsl
' :apply-templates /></td></xsl:template><xsl:template
 match="description"><td
'  xmlns=""><xsl:apply-templates /></td></xsl:template></xsl:transform></Trans
' form>
' 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 Exit to continue.
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.
#using <System.Security.dll>
#using <System.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::IO;
using namespace System::Xml;
using namespace System::Security::Cryptography;
using namespace System::Security::Cryptography::Xml;
using namespace System::Text;

ref class Class1
{
public:
   [STAThread]
   static void Main()
   {
      XmlDocument^ productsXml = LoadProducts();
      XmlNodeList^ xsltNodeList = GetXsltAsNodeList();
      TransformDoc( productsXml, xsltNodeList );
      
      // Use XmlDsigXsltTransform to resolve a Uri.
      Uri^ baseUri = gcnew Uri( L"http://www.contoso.com"
 );
      String^ relativeUri = L"xml";
      Uri^ absoluteUri = ResolveUris( baseUri, relativeUri );
      Console::WriteLine( L"This sample completed successfully; "
      L"press Enter to exit." );
      Console::ReadLine();
   }

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

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

         // Load the Xml document to perform the tranform on.
         XmlNamespaceManager^ namespaceManager;
         namespaceManager = gcnew XmlNamespaceManager( xmlDoc->NameTable );
         XmlNodeList^ productsNodeList;
         productsNodeList = xmlDoc->SelectNodes( L"//.",
 namespaceManager );
         xmlTransform->LoadInput( productsNodeList );

         // Retrieve the output from the transform.
         Stream^ outputStream = (Stream^)xmlTransform->GetOutput(
            System::IO::Stream::typeid );

         // Read the output stream into a stream reader.
         StreamReader^ streamReader = gcnew 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( L"\nResult of transformation: {0}", outputMessage
 );
         ShowTransformProperties( xmlTransform );
      }
      catch ( Exception^ ex ) 
      {
         Console::WriteLine( L"Caught exception in TransformDoc
 method: {0}", ex );
      }
   }

   static XmlNodeList^ GetXsltAsNodeList()
   {
      String^ transformXml = L"<xsl:transform version='1.0' ";
      transformXml = String::Concat( transformXml,
         L"xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>"
 );
      transformXml = String::Concat( transformXml,
         L"<xsl:template match='products'>" );
      transformXml = String::Concat( transformXml,
         L"<table><tr><td>ProductId</td><td>Name</td></tr>"
 );
      transformXml = String::Concat( transformXml,
         L"<xsl:apply-templates/></table></xsl:template>"
 );
      transformXml = String::Concat( transformXml,
         L"<xsl:template match='product'><tr>" );
      transformXml = String::Concat( transformXml,
         L"<xsl:apply-templates/></tr></xsl:template>"
 );
      transformXml = String::Concat( transformXml,
         L"<xsl:template match='productid'><td>" );
      transformXml = String::Concat( transformXml,
         L"<xsl:apply-templates/></td></xsl:template>"
 );
      transformXml = String::Concat( transformXml,
         L"<xsl:template match='description'><td>" );
      transformXml = String::Concat( transformXml,
         L"<xsl:apply-templates/></td></xsl:template>"
 );
      transformXml = String::Concat( transformXml,
         L"</xsl:transform>" );
      Console::WriteLine( L"\nCreated the following Xslt tranform:" );
      Console::WriteLine( transformXml );
      XmlDocument^ xmlDoc = gcnew XmlDocument;
      xmlDoc->LoadXml( transformXml );
      return xmlDoc->GetElementsByTagName( L"xsl:transform"
 );
   }

   // Encrypt the text in the specified XmlDocument.
   static void ShowTransformProperties( XmlDsigXsltTransform^
 xmlTransform )
   {
      String^ classDescription = xmlTransform->ToString();
      Console::WriteLine( L"\n** Summary for {0} **",
 classDescription );
      
      // Retrieve the XML representation of the current transform.
      XmlElement^ xmlInTransform = xmlTransform->GetXml();
      Console::WriteLine( L"Xml representation of the current transform:\n{0}"
,
         xmlInTransform->OuterXml );
      
      // Ensure the transform is using the proper algorithm.
      xmlTransform->Algorithm = SignedXml::XmlDsigXsltTransformUrl;
      Console::WriteLine( L"Algorithm used: {0}", classDescription );
      
      // Retrieve the valid input types for the current transform.
      array<Type^>^validInTypes = xmlTransform->InputTypes;
      Console::WriteLine( L"Transform accepts the following inputs:" );
      for ( int i = 0; i < validInTypes->Length;
 i++ )
      {
         Console::WriteLine( L"\t{0}", validInTypes[ i ] );

      }
      
      array<Type^>^validOutTypes = xmlTransform->OutputTypes;
      Console::WriteLine( L"Transform outputs in the following
 types:" );
      for ( int i = validOutTypes->Length
 - 1; i >= 0; i-- )
      {
         Console::WriteLine( L"\t {0}", validOutTypes[ i ] );
         if ( validOutTypes[ i ] == Object::typeid )
         {
            Object^ outputObject = xmlTransform->GetOutput();
         }
      }
   }

   // Create an XML document describing various products.
   static XmlDocument^ LoadProducts()
   {
      String^ contosoProducts = L"<?xml version='1.0'?>";
      contosoProducts = String::Concat( contosoProducts,
         L"<products>" );
      contosoProducts = String::Concat( contosoProducts,
         L"<product><productid>1</productid>" );
      contosoProducts = String::Concat( contosoProducts,
         L"<description>Widgets</description></product>"
 );
      contosoProducts = String::Concat( contosoProducts,
         L"<product><productid>2</productid>" );
      contosoProducts = String::Concat( contosoProducts,
         L"<description>Gadgits</description></product>"
 );
      contosoProducts = String::Concat( contosoProducts,
         L"</products>" );
      Console::WriteLine(
         L"\nCreated the following Xml document for tranformation:"
 );
      Console::WriteLine( contosoProducts );
      XmlDocument^ xmlDoc = gcnew XmlDocument;
      xmlDoc->LoadXml( contosoProducts );
      return xmlDoc;
   }

   // Resolve the specified base and relative Uri's .
   static Uri^ ResolveUris( Uri^ baseUri, String^ relativeUri
 )
   {
      XmlUrlResolver^ xmlResolver = gcnew XmlUrlResolver;
      xmlResolver->Credentials =
         System::Net::CredentialCache::DefaultCredentials;

      XmlDsigXsltTransform^ xmlTransform = gcnew XmlDsigXsltTransform;
      xmlTransform->Resolver = xmlResolver;

      Uri^ absoluteUri = xmlResolver->ResolveUri( baseUri, relativeUri );
      if ( absoluteUri != nullptr )
      {
         Console::WriteLine(
         L"\nResolved the base Uri and relative Uri to the
 following:" );
         Console::WriteLine( absoluteUri );
      }
      else
      {
         Console::WriteLine( L"Unable to resolve the base
 Uri and relative Uri" );
      }

      return absoluteUri;
   }
};

int main()
{
   Class1::Main();
}

//
// 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.
import System.*;
import System.IO.*;
import System.Xml.*;
import System.Security.Cryptography.*;
import System.Security.Cryptography.Xml.*;
import System.Text.*;

class Class1
{
    /** @attribute STAThread()
     */
    public 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();
    } //main

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

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

            xmlTransform.LoadInput(productsNodeList);

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

            // 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 (System.Exception ex) {
            Console.WriteLine("Caught exception in TransformDoc
 method: " 
                + ex.ToString());
        }
    } //TransformDoc

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

    // 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.get_OuterXml());
        // Ensure the transform is using the proper algorithm.
        xmlTransform.set_Algorithm(
            SignedXml.XmlDsigXsltTransformUrl);

        Console.WriteLine("Algorithm used: " + classDescription);
        // Retrieve the valid input types for the current transform.
        Type validInTypes[] = xmlTransform.get_InputTypes();

        Console.WriteLine("Transform accepts the following inputs:");
        for (int i = 0; i < validInTypes.get_Length();
 i++) {
            Console.WriteLine("\t" + validInTypes.get_Item(i).ToString());
        }
        Type validOutTypes[] = xmlTransform.get_OutputTypes();

        Console.WriteLine("Transform outputs in the following
 types:");
        for (int i = validOutTypes.get_Length()
 - 1; i >= 0; i--) {
            Console.WriteLine("\t " + validOutTypes.get_Item(i).ToString());
            if (validOutTypes.get_Item(i).Equals(Object.class.ToType()))
 {
                Object outputObject = xmlTransform.GetOutput();
            }
        }  
    } //ShowTransformProperties

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

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

        XmlDsigXsltTransform xmlTransform = new XmlDsigXsltTransform();
        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:
//
// 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.
継承階層継承階層
System.Object
   System.Security.Cryptography.Xml.Transform
    System.Security.Cryptography.Xml.XmlDsigXsltTransform
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
XmlDsigXsltTransform メンバ
System.Security.Cryptography.Xml 名前空間

XmlDsigXsltTransform コンストラクタ ()

XmlDsigXsltTransform クラス新しインスタンス初期化します。

名前空間: System.Security.Cryptography.Xml
アセンブリ: System.Security (system.security.dll 内)
構文構文

Dim instance As New XmlDsigXsltTransform
public XmlDsigXsltTransform ()
public:
XmlDsigXsltTransform ()
public XmlDsigXsltTransform ()
public function XmlDsigXsltTransform ()
使用例使用例

XmlDsigXsltTransform クラスエンベロープ シグネチャと共に使用しXML ドキュメント署名および検証を行うコード例次に示します

'
' This example signs an XML file using an
' envelope signature. It then verifies the 
' signed XML.
'
Imports System
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.Xml
Imports System.Text
Imports System.Xml



Module SignVerifyEnvelope


    Sub Main(ByVal args() As
 String)
        ' Generate a signing key.
        Dim Key As New RSACryptoServiceProvider()

        Dim xsl As String
 = "<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...")
            Dim result As Boolean
 = VerifyXmlFile("SignedExample.xml")

            ' Display the results of the signature verification to \
            ' the console.
            If result Then
                Console.WriteLine("The XML signature is valid.")
            Else
                Console.WriteLine("The XML signature is not valid.")
            End If
        Catch e As CryptographicException
            Console.WriteLine(e.Message)
        Finally
            Key.Clear()
        End Try

    End Sub


    ' Sign an XML file and save the signature in a new file.
    Sub SignXmlFile(ByVal FileName As
 String, ByVal SignedFileName As
 String, ByVal Key As RSA, ByVal XSLString As String)
        ' Create a new XML document.
        Dim doc As 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.
        Dim signedXml As New
 SignedXml(doc)

        ' Add the key to the SignedXml document. 
        signedXml.SigningKey = Key

        ' Create a reference to be signed.
        Dim reference As New
 Reference()
        reference.Uri = ""

        ' Add an enveloped transformation to the reference.
        Dim env As New XmlDsigEnvelopedSignatureTransform()
        reference.AddTransform(env)

        ' Create an XmlDsigXPathTransform object using 
        ' the helper method 'CreateXPathTransform' defined
        ' later in this sample.
        Dim XsltTransform As XmlDsigXsltTransform
 = 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).
        Dim keyInfo As New
 KeyInfo()
        keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA)))
        signedXml.KeyInfo = keyInfo

        ' Compute the signature.
        signedXml.ComputeSignature()

        ' Get the XML representation of the signature and save
        ' it to an XmlElement object.
        Dim xmlDigitalSignature As XmlElement
 = 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.
        Dim xmltw As New
 XmlTextWriter(SignedFileName, New UTF8Encoding(False))
        doc.WriteTo(xmltw)
        xmltw.Close()

    End Sub

    ' Verify the signature of an XML file and return the result.
    Function VerifyXmlFile(ByVal Name As
 String) As [Boolean]
        ' Create a new XML document.
        Dim xmlDocument As 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.
        Dim signedXml As New
 SignedXml(xmlDocument)

        ' Find the "Signature" node and create a new
        ' XmlNodeList object.
        Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature")

        ' Load the signature node.
        signedXml.LoadXml(CType(nodeList(0), XmlElement))

        ' Check the signature and return the result.
        Return signedXml.CheckSignature()

    End Function


    ' Create the XML that represents the transform.
    Function CreateXsltTransform(ByVal xsl
 As String) As XmlDsigXsltTransform
        Dim doc As New XmlDocument()
        doc.LoadXml(xsl)

        Dim xform As New
 XmlDsigXsltTransform()
        xform.LoadInnerXml(doc.ChildNodes)

        Return xform

    End Function


    ' Create example data to sign.
    Sub CreateSomeXml(ByVal FileName As
 String)
        ' Create a new XmlDocument object.
        Dim document As New
 XmlDocument()

        ' Create a new XmlNode object.
        Dim node As XmlNode = document.CreateNode(XmlNodeType.Element,
 "", "MyXML", "Don't_Sign")

        ' Append the node to the document.
        document.AppendChild(node)

        ' Create a new XmlNode object.
        Dim subnode As XmlNode = 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.
        Dim xmltw As New
 XmlTextWriter(FileName, New UTF8Encoding(False))
        document.WriteTo(xmltw)
        xmltw.Close()

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

        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();
    }
}
//
// This example signs an XML file using an
// envelope signature. It then verifies the 
// signed XML.
//
#using <System.Xml.dll>
#using <System.Security.dll>
#using <System.dll>

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::Security::Cryptography::Xml;
using namespace System::Text;
using namespace System::Xml;

// Create the XML that represents the transform.
static XmlDsigXsltTransform^ CreateXsltTransform( String^ xsl
 )
{
   XmlDocument^ doc = gcnew XmlDocument;
   doc->LoadXml( xsl );
   XmlDsigXsltTransform^ xform = gcnew XmlDsigXsltTransform;
   xform->LoadInnerXml( doc->ChildNodes );
   return xform;
}


// Sign an XML file and save the signature in a new file.
static void SignXmlFile( String^ FileName,
 String^ SignedFileName, RSA^ Key, String^ XSLString )
{
   
   // Create a new XML document.
   XmlDocument^ doc = gcnew XmlDocument;
   
   // Format the document to ignore white spaces.
   doc->PreserveWhitespace = false;
   
   // Load the passed XML file using it's name.
   doc->Load( gcnew XmlTextReader( FileName ) );
   
   // Create a SignedXml object.
   SignedXml^ signedXml = gcnew SignedXml( doc );
   
   // Add the key to the SignedXml document. 
   signedXml->SigningKey = Key;
   
   // Create a reference to be signed.
   Reference^ reference = gcnew Reference;
   reference->Uri = L"";
   
   // Add an enveloped transformation to the reference.
   XmlDsigEnvelopedSignatureTransform^ env = gcnew 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 = gcnew KeyInfo;
   keyInfo->AddClause( gcnew RSAKeyValue( dynamic_cast<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 = gcnew XmlTextWriter( SignedFileName,gcnew UTF8Encoding(
 false ) );
   doc->WriteTo( xmltw );
   xmltw->Close();
}


// Verify the signature of an XML file and return the result.
static Boolean VerifyXmlFile( String^ Name )
{
   
   // Create a new XML document.
   XmlDocument^ xmlDocument = gcnew 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 = gcnew SignedXml( xmlDocument );
   
   // Find the "Signature" node and create a new
   // XmlNodeList object.
   XmlNodeList^ nodeList = xmlDocument->GetElementsByTagName( L"Signature"
 );
   
   // Load the signature node.
   signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList->Item( 0 ))
 );
   
   // Check the signature and return the result.
   return signedXml->CheckSignature();
}


// Create example data to sign.
static void CreateSomeXml( String^ FileName
 )
{
   
   // Create a new XmlDocument object.
   XmlDocument^ document = gcnew XmlDocument;
   
   // Create a new XmlNode object.
   XmlNode^ node = document->CreateNode( XmlNodeType::Element, L"",
 L"MyXML", L"Don't_Sign" );
   
   // Append the node to the document.
   document->AppendChild( node );
   
   // Create a new XmlNode object.
   XmlNode^ subnode = document->CreateNode( XmlNodeType::Element, L"",
 L"ElementToTransform", L"Sign" );
   
   // Add some text to the node.
   subnode->InnerText = L"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 = gcnew XmlTextWriter( FileName,gcnew UTF8Encoding( false
 ) );
   document->WriteTo( xmltw );
   xmltw->Close();
}

int main()
{
   
   // Generate a signing key.
   RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider;
   String^ xsl = L"\r\n    <xs:transform xmlns:xs='http://www.w3.org/1999/XSL/Transform'
 version='1.0'>\r\n        <xs:template match='/'>\r\n            <xs:apply-templates/>\r\n
        </xs:template>\r\n        <xs:template match='ElementToTransform'> \r\n            <transformedElement/>\r\n        </xs:template>\r\n    </xs:transform>";
   try
   {
      
      // Create an XML file to sign.
      CreateSomeXml( L"Example.xml" );
      Console::WriteLine( L"New XML file created." );
      
      // Sign the XML that was just created and save it in a 
      // new file.
      SignXmlFile( L"Example.xml", L"SignedExample.xml", Key,
 xsl );
      Console::WriteLine( L"XML file signed." );
      
      // Verify the signature of the signed XML.
      Console::WriteLine( L"Verifying signature..." );
      bool result = VerifyXmlFile( L"SignedExample.xml"
 );
      
      // Display the results of the signature verification to \
      // the console.
      if ( result )
      {
         Console::WriteLine( L"The XML signature is valid." );
      }
      else
      {
         Console::WriteLine( L"The XML signature is not valid." );
      }
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( e->Message );
   }
   finally
   {
      Key->Clear();
   }

   return 1;
}

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
XmlDsigXsltTransform クラス
XmlDsigXsltTransform メンバ
System.Security.Cryptography.Xml 名前空間

XmlDsigXsltTransform コンストラクタ (Boolean)

コメント指定されている場合は、そのコメントを持つ XmlDsigXsltTransform クラス新しインスタンス初期化します。

名前空間: System.Security.Cryptography.Xml
アセンブリ: System.Security (system.security.dll 内)
構文構文

Public Sub New ( _
    includeComments As Boolean _
)
Dim includeComments As Boolean

Dim instance As New XmlDsigXsltTransform(includeComments)
public XmlDsigXsltTransform (
    bool includeComments
)
public:
XmlDsigXsltTransform (
    bool includeComments
)
public XmlDsigXsltTransform (
    boolean includeComments
)
public function XmlDsigXsltTransform (
    includeComments : boolean
)

パラメータ

includeComments

コメント含め場合trueそれ以外場合false

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
XmlDsigXsltTransform クラス
XmlDsigXsltTransform メンバ
System.Security.Cryptography.Xml 名前空間

XmlDsigXsltTransform コンストラクタ

XmlDsigXsltTransform クラス新しインスタンス初期化します。
オーバーロードの一覧オーバーロードの一覧

名前 説明
XmlDsigXsltTransform () XmlDsigXsltTransform クラス新しインスタンス初期化します。
XmlDsigXsltTransform (Boolean) コメント指定されている場合は、そのコメントを持つ XmlDsigXsltTransform クラス新しインスタンス初期化します。
参照参照

関連項目

XmlDsigXsltTransform クラス
XmlDsigXsltTransform メンバ
System.Security.Cryptography.Xml 名前空間

XmlDsigXsltTransform プロパティ


XmlDsigXsltTransform メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetDigestedOutput  派生クラスオーバーライドされた場合は、Transform オブジェクト関連付けられているダイジェスト返します。 ( Transform から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetOutput オーバーロードされますオーバーライドされます現在の XmlDsigXsltTransform オブジェクト出力返します
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド GetXml  現在の Transform オブジェクトXML 表現返します。 ( Transform から継承されます。)
パブリック メソッド LoadInnerXml オーバーライドされます指定した XmlNodeList オブジェクト<Transform> 要素変換固有内容として解析し現在の XmlDsigXsltTransform オブジェクト内部状態を <Transform> 要素一致するように設定します
パブリック メソッド LoadInput オーバーライドされます指定した入力現在の XmlDsigXsltTransform オブジェクト読み込みます。
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

XmlDsigXsltTransform クラス
System.Security.Cryptography.Xml 名前空間

XmlDsigXsltTransform メンバ

W3C によって定義された、デジタル署名XSLT 変換表します

XmlDsigXsltTransform データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
  名前 説明
パブリック メソッド XmlDsigXsltTransform オーバーロードされます。 XmlDsigXsltTransform クラス新しインスタンス初期化します。
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetDigestedOutput  派生クラスオーバーライドされた場合は、Transform オブジェクト関連付けられているダイジェスト返します。 (Transform から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetOutput オーバーロードされますオーバーライドされます現在の XmlDsigXsltTransform オブジェクト出力返します
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド GetXml  現在の Transform オブジェクトXML 表現返します。 (Transform から継承されます。)
パブリック メソッド LoadInnerXml オーバーライドされます指定した XmlNodeList オブジェクト<Transform> 要素変換固有内容として解析し現在の XmlDsigXsltTransform オブジェクト内部状態を <Transform> 要素一致するように設定します
パブリック メソッド LoadInput オーバーライドされます指定した入力現在の XmlDsigXsltTransform オブジェクト読み込みます。
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

XmlDsigXsltTransform クラス
System.Security.Cryptography.Xml 名前空間


このページでは「.NET Framework クラス ライブラリ リファレンス」からXmlDsigXsltTransformを検索した結果を表示しています。
Weblioに収録されているすべての辞書からXmlDsigXsltTransformを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からXmlDsigXsltTransform を検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「XmlDsigXsltTransform」の関連用語

XmlDsigXsltTransformのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



XmlDsigXsltTransformのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS