SignedXml Clase

Definición

Proporciona un contenedor en un objeto de firma XML base para facilitar la creación de firmas XML.Provides a wrapper on a core XML signature object to facilitate creating XML signatures.

public ref class SignedXml
public class SignedXml
type SignedXml = class
Public Class SignedXml
Herencia
SignedXml

Ejemplos

En el ejemplo de código siguiente se muestra cómo firmar y comprobar un documento XML completo mediante una firma con doble cifrado.The following code example shows how to sign and verify an entire XML document using an enveloped signature.

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

// Sign an XML file and save the signature in a new file. This method does not  
// save the public key within the XML file.  This file cannot be verified unless  
// the verifying code has the key with which it was signed.
void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key )
{
   
   // Create a new XML document.
   XmlDocument^ doc = gcnew XmlDocument;
   
   // Load the passed XML file using its 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 = "";
   
   // Add an enveloped transformation to the reference.
   XmlDsigEnvelopedSignatureTransform^ env = gcnew XmlDsigEnvelopedSignatureTransform;
   reference->AddTransform( env );
   
   // Add the reference to the SignedXml object.
   signedXml->AddReference( reference );
   
   // Compute the signature.
   signedXml->ComputeSignature();
   
   // Get the XML representation of the signature and save
   // it to an XmlElement object.
   XmlElement^ xmlDigitalSignature = signedXml->GetXml();
   
   // Append the element to the XML document.
   doc->DocumentElement->AppendChild( doc->ImportNode( xmlDigitalSignature, true ) );
   if ( (doc->FirstChild)->GetType() == XmlDeclaration::typeid )
   {
      doc->RemoveChild( doc->FirstChild );
   }

   
   // 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 against an asymmetric 
// algorithm and return the result.
Boolean VerifyXmlFile( String^ Name, RSA^ Key )
{
   
   // Create a new XML document.
   XmlDocument^ xmlDocument = gcnew XmlDocument;
   
   // 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( "Signature" );
   
   // Load the signature node.
   signedXml->LoadXml( safe_cast<XmlElement^>(nodeList->Item( 0 )) );
   
   // Check the signature and return the result.
   return signedXml->CheckSignature( Key );
}


// Create example data to sign.
void CreateSomeXml( String^ FileName )
{
   
   // Create a new XmlDocument Object*.
   XmlDocument^ document = gcnew XmlDocument;
   
   // Create a new XmlNode object.
   XmlNode^ node = document->CreateNode( XmlNodeType::Element, "", "MyElement", "samples" );
   
   // Add some text to the node.
   node->InnerText = "Example text to be signed.";
   
   // Append the node to the document.
   document->AppendChild( node );
   
   // Save the XML document to the file name specified.
   XmlTextWriter^ xmltw = gcnew XmlTextWriter( FileName,gcnew UTF8Encoding( false ) );
   document->WriteTo( xmltw );
   xmltw->Close();
}

int main()
{
   try
   {
      
      // Generate a signing key.
      RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider;
      
      // Create an XML file to sign.
      CreateSomeXml( "Example.xml" );
      Console::WriteLine( "New XML file created." );
      
      // Sign the XML that was just created and save it in a 
      // new file.
      SignXmlFile( "Example.xml", "signedExample.xml", Key );
      Console::WriteLine( "XML file signed." );
      
      // Verify the signature of the signed XML.
      Console::WriteLine( "Verifying signature..." );
      bool result = VerifyXmlFile( "SignedExample.xml", Key );
      
      // 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 );
   }

}

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

public class SignVerifyEnvelope
{

    public static void Main(String[] args)
    {
        try
        {
           // Generate a signing key.
           RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

           // Create an XML file to sign.
           CreateSomeXml("Example.xml");
           Console.WriteLine("New XML file created."); 

           // Sign the XML that was just created and save it in a 
           // new file.
           SignXmlFile("Example.xml", "signedExample.xml", Key);
           Console.WriteLine("XML file signed."); 

           // Verify the signature of the signed XML.
           Console.WriteLine("Verifying signature...");
           bool result = VerifyXmlFile("SignedExample.xml", Key);

           // Display the results of the signature verification to 
           // the console.
           if(result)
           {
               Console.WriteLine("The XML signature is valid.");
           }
           else
           {
            Console.WriteLine("The XML signature is not valid.");
           }
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }


    // Sign an XML file and save the signature in a new file. This method does not  
    // save the public key within the XML file.  This file cannot be verified unless  
    // the verifying code has the key with which it was signed.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Load the passed XML file using its name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document. 
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
        
        if (doc.FirstChild is XmlDeclaration)  
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
        doc.WriteTo(xmltw);
        xmltw.Close();
    }

    // Verify the signature of an XML file against an asymetric 
    // algorithm and return the result.
    public static Boolean VerifyXmlFile(String Name, RSA Key)
    {
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

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


    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
    {
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode  node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");
        
        // Add some text to the node.
        node.InnerText = "Example text to be signed.";

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

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
        document.WriteTo(xmltw);
        xmltw.Close();
    }
}
'
' This example signs an XML file using an
' envelope signature. It then verifies the 
' signed XML.
'
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.Xml
Imports System.Text
Imports System.Xml



Public Class SignVerifyEnvelope
   
   Overloads Public Shared Sub Main(args() As [String])
      Try
         ' Generate a signing key.
         Dim Key As New RSACryptoServiceProvider()
         
         ' Create an XML file to sign.
         CreateSomeXml("Example.xml")
         Console.WriteLine("New XML file created.")
         
         ' Sign the XML that was just created and save it in a 
         ' new file.
         SignXmlFile("Example.xml", "signedExample.xml", Key)
         Console.WriteLine("XML file signed.")
         
         ' Verify the signature of the signed XML.
         Console.WriteLine("Verifying signature...")
         Dim result As Boolean = VerifyXmlFile("SignedExample.xml", Key)
         
         ' 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)
      End Try
   End Sub 
   
   
   
   ' Sign an XML file and save the signature in a new file. This method does not  
   ' save the public key within the XML file.  This file cannot be verified unless  
   ' the verifying code has the key with which it was signed.
   Public Shared Sub SignXmlFile(FileName As String, SignedFileName As String, Key As RSA)
      ' Create a new XML document.
      Dim doc As New XmlDocument()
      
      ' Load the passed XML file using its 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)
      
      ' Add the reference to the SignedXml object.
      signedXml.AddReference(reference)
      
      ' 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))
      
      If TypeOf doc.FirstChild Is XmlDeclaration Then
         doc.RemoveChild(doc.FirstChild)
      End If
      
      ' 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 against an asymetric 
   ' algorithm and return the result.
   Public Shared Function VerifyXmlFile(Name As [String], Key As RSA) As [Boolean]
      ' Create a new XML document.
      Dim xmlDocument As New XmlDocument()
      
      ' 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(Key)
   End Function 
   
   
   
   ' Create example data to sign.
   Public Shared Sub CreateSomeXml(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, "", "MyElement", "samples")
      
      ' Add some text to the node.
      node.InnerText = "Example text to be signed."
      
      ' Append the node to the document.
      document.AppendChild(node)
      
      ' Save the XML document to the file name specified.
      Dim xmltw As New XmlTextWriter(FileName, New UTF8Encoding(False))
      document.WriteTo(xmltw)
      xmltw.Close()
   End Sub 
End Class 

En el ejemplo de código siguiente se muestra cómo firmar y comprobar un solo elemento de un documento XML mediante una firma de envoltura.The following code example shows how to sign and verify a single element of an XML document using an enveloping signature.

//
// 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::Xml;
using namespace System::Text;
using namespace System::Xml;

// Sign an XML file and save the signature in a new file.
static void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key, array<String^>^ElementsToSign )
{
   
   // Check the arguments.  
   if ( FileName == nullptr )
      throw gcnew ArgumentNullException( L"FileName" );

   if ( SignedFileName == nullptr )
      throw gcnew ArgumentNullException( L"SignedFileName" );

   if ( Key == nullptr )
      throw gcnew ArgumentNullException( L"Key" );

   if ( ElementsToSign == nullptr )
      throw gcnew ArgumentNullException( L"ElementsToSign" );

   
   // 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;
   
   // Loop through each passed element to sign 
   // and create a reference.
   System::Collections::IEnumerator^ myEnum = ElementsToSign->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum->Current);
      
      // Create a reference to be signed.
      Reference^ reference = gcnew Reference;
      reference->Uri = s;
      
      // Add an enveloped transformation to the reference.
      XmlDsigEnvelopedSignatureTransform^ env = gcnew XmlDsigEnvelopedSignatureTransform;
      reference->AddTransform( env );
      
      // Add the reference to the SignedXml object.
      signedXml->AddReference( reference );
   }

   
   // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
   KeyInfo^ keyInfo = 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 ) );
   if ( dynamic_cast<XmlDeclaration^>(doc->FirstChild) )
   {
      doc->RemoveChild( doc->FirstChild );
   }

   
   // 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 )
{
   
   // Check the arguments.  
   if ( Name == nullptr )
      throw gcnew ArgumentNullException( L"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();
}

int main()
{
   
   // Generate a signing key.
   RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider;
   try
   {
      
      // Specify an element to sign. 
      array<String^>^elements = {L"#tag1"};
      
      // Sign an XML file and save the signature to a 
      // new file.
      SignXmlFile( L"Test.xml", L"SignedExample.xml", Key, elements );
      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
   {
      
      // Clear resources associated with the 
      // RSACryptoServiceProvider.
      Key->Clear();
   }

   return 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.Xml;
using System.Text;
using System.Xml;

public class SignVerifyEnvelope
{

    public static void Main(String[] args)
    {
        // Generate a signing key.
       RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

       try
       {
           // Specify an element to sign. 
           string[] elements =  { "#tag1" };

           // Sign an XML file and save the signature to a 
           // new file.
           SignXmlFile("Test.xml", "SignedExample.xml", Key, elements);
           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
       {
           // Clear resources associated with the 
           // RSACryptoServiceProvider.
           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[] ElementsToSign)
    {
        // Check the arguments.  
        if (FileName == null)
            throw new ArgumentNullException("FileName");
        if (SignedFileName == null)
            throw new ArgumentNullException("SignedFileName");
        if (Key == null)
            throw new ArgumentNullException("Key");
        if (ElementsToSign == null)
            throw new ArgumentNullException("ElementsToSign");

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

        // Loop through each passed element to sign 
        // and create a reference.
        foreach (string s in ElementsToSign)
        {
            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = s;

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

        }



        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
        doc.WriteTo(xmltw);
        xmltw.Close();
    }
    // Verify the signature of an XML file and return the result.
    public static Boolean VerifyXmlFile(String Name)
    {
        // Check the arguments.  
        if (Name == null)
            throw new ArgumentNullException("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();
    }
}
' This example signs an XML file using an
' envelope signature. It then verifies the 
' signed XML.
'
Imports System.Security.Cryptography
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()

        Try
            ' Specify an element to sign. 
            Dim elements As String() = New String() {"#tag1"}

            ' Sign an XML file and save the signature to a 
            ' new file.
            SignXmlFile("Test.xml", "SignedExample.xml", Key, elements)
            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
            ' Clear resources associated with the 
            ' RSACryptoServiceProvider.
            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 ElementsToSign() As String)
        ' Check the arguments.  
        If FileName Is Nothing Then
            Throw New ArgumentNullException("FileName")
        End If
        If SignedFileName Is Nothing Then
            Throw New ArgumentNullException("SignedFileName")
        End If
        If Key Is Nothing Then
            Throw New ArgumentNullException("Key")
        End If
        If ElementsToSign Is Nothing Then
            Throw New ArgumentNullException("ElementsToSign")
        End If
        ' 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

        ' Loop through each passed element to sign 
        ' and create a reference.
        Dim s As String
        For Each s In ElementsToSign
            ' Create a reference to be signed.
            Dim reference As New Reference()
            reference.Uri = s

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

            ' Add the reference to the SignedXml object.
            signedXml.AddReference(reference)
        Next s

        ' 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))


        If TypeOf doc.FirstChild Is XmlDeclaration Then
            doc.RemoveChild(doc.FirstChild)
        End If

        ' 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]
        ' Check the arguments.  
        If Name Is Nothing Then
            Throw New ArgumentNullException("Name")
        End If
        ' 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
End Module

Comentarios

La SignedXml clase es la implementación de .net de la especificación de procesamiento y la sintaxis de firma XMLde World Wide Web Consortium (W3C), también conocida como XMLDSIG (firma digital XML).The SignedXml class is the .NET implementation of the World Wide Web Consortium (W3C) XML Signature Syntax and Processing Specification, also known as XMLDSIG (XML Digital Signature). XMLDSIG es una manera interoperable y basada en estándares de firmar y comprobar todo o parte de un documento XML u otros datos que se puedan direccionar desde un identificador uniforme de recursos (URI).XMLDSIG is a standards-based, interoperable way to sign and verify all or part of an XML document or other data that is addressable from a Uniform Resource Identifier (URI).

Utilice la SignedXml clase siempre que necesite compartir datos XML firmados entre aplicaciones u organizaciones de una manera estándar.Use the SignedXml class whenever you need to share signed XML data between applications or organizations in a standard way. Los datos firmados mediante esta clase se pueden comprobar mediante cualquier implementación compatible de la especificación del W3C para XMLDSIG.Any data signed using this class can be verified by any conforming implementation of the W3C specification for XMLDSIG.

La SignedXml clase permite crear los tres tipos siguientes de firmas digitales XML:The SignedXml class allows you to create the following three kinds of XML digital signatures:

Tipo de firmaSignature Type DescripciónDescription
Firma con doble cifradoEnveloped signature La firma está incluida en el elemento XML que se está firmando.The signature is contained within the XML element being signed.
Firma de envolturaEnveloping signature El XML firmado está contenido dentro del <Signature> elemento.The signed XML is contained within the <Signature> element.
Firma separada internaInternal detached signature La firma y el XML firmado están en el mismo documento, pero ningún elemento contiene el otro.The signature and signed XML are in the same document, but neither element contains the other.

También hay un cuarto tipo de firma denominada una firma desasociada externa que es cuando los datos y la firma están en documentos XML independientes.There is also a fourth kind of signature called an external detached signature which is when the data and signature are in separate XML documents. La clase no admite las SignedXml signaturas desasociadas externas.External detached signatures are not supported by the SignedXml class.

La estructura de una firma XMLThe structure of an XML Signature

XMLDSIG crea un <Signature> elemento, que contiene una firma digital de un documento XML u otros datos direccionables desde un URI.XMLDSIG creates a <Signature> element, which contains a digital signature of an XML document or other data that is addressable from a URI. El <Signature> elemento puede contener opcionalmente información sobre dónde encontrar una clave que comprobará la firma y qué algoritmo criptográfico se usó para firmar.The <Signature> element can optionally contain information about where to find a key that will verify the signature and which cryptographic algorithm was used for signing. La estructura básica es la siguiente:The basic structure is as follows:

<Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">  
    <SignedInfo>  
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>  
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>  
      <Reference URI="">  
        <Transforms>  
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>  
        </Transforms>  
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>  
        <DigestValue>Base64EncodedValue==</DigestValue>  
      </Reference>  
    </SignedInfo>  
    <SignatureValue>AnotherBase64EncodedValue===</SignatureValue>  
</Signature>

Las partes principales de esta estructura son:The main parts of this structure are:

  • El elemento <CanonicalizationMethod>The <CanonicalizationMethod> element

    Especifica las reglas para volver a escribir Signature el elemento de XML/Text en bytes para la validación de la firma.Specifies the rules for rewriting the Signature element from XML/text into bytes for signature validation. El valor predeterminado en .net es http://www.w3.org/TR/2001/REC-xml-c14n-20010315, que identifica un algoritmo de confianza.The default value in .NET is http://www.w3.org/TR/2001/REC-xml-c14n-20010315, which identifies a trustworthy algorithm. Este elemento se representa mediante la SignedInfo.CanonicalizationMethod propiedad.This element is represented by the SignedInfo.CanonicalizationMethod property.

  • El elemento <SignatureMethod>The <SignatureMethod> element

    Especifica el algoritmo utilizado para la generación y validación de firmas, que se aplicó <Signature> al elemento para generar el valor <SignatureValue>en.Specifies the algorithm used for signature generation and validation, which was applied to the <Signature> element to produce the value in <SignatureValue>. En el ejemplo anterior, el valor http://www.w3.org/2000/09/xmldsig#rsa-sha1 identifica una firma de RSA PKCS1 SHA-1.In the previous example, the value http://www.w3.org/2000/09/xmldsig#rsa-sha1 identifies an RSA PKCS1 SHA-1 signature. Debido a problemas de colisión con SHA-1, Microsoft recomienda un modelo de seguridad basado en SHA-256 o superior.Due to collision problems with SHA-1, Microsoft recommends a security model based on SHA-256 or better. Este elemento se representa mediante la SignatureMethod propiedad.This element is represented by the SignatureMethod property.

  • El elemento <SignatureValue>The <SignatureValue> element

    Especifica la firma <Signature> criptográfica del elemento.Specifies the cryptographic signature for the <Signature> element. Si esta firma no se comprueba, se alteró alguna parte <Signature> del bloque y el documento se considera no válido.If this signature does not verify, then some portion of the <Signature> block was tampered with, and the document is considered invalid. Siempre que el valor <CanonicalizationMethod> sea de confianza, este valor es muy resistente a la manipulación.As long as the <CanonicalizationMethod> value is trustworthy, this value is highly resistant to tampering. Este elemento se representa mediante la SignatureValue propiedad.This element is represented by the SignatureValue property.

  • URI Atributo<Reference> del elemento.The URI attribute of the <Reference> element

    Especifica un objeto de datos mediante una referencia de URI.Specifies a data object using a URI reference. Este atributo se representa mediante la Reference.Uri propiedad.This attribute is represented by the Reference.Uri property.

    • No especificar el URI atributo, es decir, establecer la Reference.Uri propiedad en null, significa que se espera que la aplicación receptora Conozca la identidad del objeto.Not specifying the URI attribute, that is, setting the Reference.Uri property to null, means that the receiving application is expected to know the identity of the object. En la mayoría de los null casos, un URI producirá una excepción.In most cases, a null URI will result in an exception being thrown. No use un null URI, a menos que la aplicación interopere con un protocolo que lo requiera.Do not use a null URI, unless your application is interoperating with a protocol which requires it.

    • Al establecer URI el atributo en una cadena vacía, se indica que el elemento raíz del documento se está firmando, un formulario de firma con doble cifrado.Setting the URI attribute to an empty string indicates that the root element of the document is being signed, a form of enveloped signature.

    • Si el valor del URI atributo comienza con #, el valor debe resolverse en un elemento del documento actual.If the value of URI attribute starts with #, then the value must resolve to an element in the current document. Este formulario se puede usar con cualquiera de los tipos de firma admitidos (firma con doble cifrado, firma de envoltura o firma desasociada interna).This form can be used with any of the supported signature types (enveloped signature, enveloping signature or internal detached signature).

    • Todo lo demás se considera una firma separada de recursos externos y no es compatible con SignedXml la clase.Anything else is considered an external resource detached signature and is not supported by the SignedXml class.

  • El elemento <Transforms>The <Transforms> element

    Contiene una lista ordenada de <Transform> elementos que describen cómo el firmante obtuvo el objeto de datos que se ha implícito.Contains an ordered list of <Transform> elements that describe how the signer obtained the data object that was digested. Un algoritmo de transformación es similar al método de canonización, pero en lugar de volver a <Signature> escribir el elemento, reescribe el contenido identificado por el URI atributo del <Reference> elemento.A transform algorithm is similar to the canonicalization method, but instead of rewriting the <Signature> element, it rewrites the content identified by the URI attribute of the <Reference> element. El elemento se representa mediante la TransformChain clase. <Transforms>The <Transforms> element is represented by the TransformChain class.

    • Cada algoritmo de transformación se define como que toma XML (un conjunto de nodos XPath) o bytes como entrada.Each transform algorithm is defined as taking either XML (an XPath node-set) or bytes as input. Si el formato de los datos actuales difiere de los requisitos de entrada de transformación, se aplican las reglas de conversión.If the format of the current data differs from the transform input requirements, conversion rules are applied.

    • Cada algoritmo de transformación se define como una generación de XML o bytes como salida.Each transform algorithm is defined as producing either XML or bytes as the output.

    • Si la salida del algoritmo de última transformación no está definida en bytes (o no se especificaron transformaciones), el método de canonización se utiliza como una transformación implícita (incluso si se especificó un algoritmo diferente <CanonicalizationMethod> en el elemento).If the output of the last transform algorithm is not defined in bytes (or no transforms were specified), then the canonicalization method is used as an implicit transform (even if a different algorithm was specified in the <CanonicalizationMethod> element).

    • Un valor de http://www.w3.org/2000/09/xmldsig#enveloped-signature para el algoritmo de transformación codifica una regla que se interpreta como quitar el <Signature> elemento del documento.A value of http://www.w3.org/2000/09/xmldsig#enveloped-signature for the transform algorithm encodes a rule which is interpreted as remove the <Signature> element from the document. De lo contrario, un comprobador de una firma con envoltorio resumiría el documento, incluida la firma, pero el firmante habría implícito el documento antes de que se aplicara la firma, dando lugar a respuestas diferentes.Otherwise, a verifier of an enveloped signature will digest the document, including the signature, but the signer would have digested the document before the signature was applied, leading to different answers.

  • El elemento <DigestMethod>The <DigestMethod> element

    Identifica el método de síntesis (hash criptográfico) que se va a aplicar en el contenido transformado identificado <Reference> por el URI atributo del elemento.Identifies the digest (cryptographic hash) method to apply on the transformed content identified by the URI attribute of the <Reference> element. Se representa mediante la Reference.DigestMethod propiedad.This is represented by the Reference.DigestMethod property.

Elección de un método de canonizaciónChoosing a canonicalization method

A menos que interopere con una especificación que requiere el uso de un valor diferente, se recomienda usar el método de canonización de .NET predeterminado, que es el algoritmo XML-C14N 1,0, cuyo http://www.w3.org/TR/2001/REC-xml-c14n-20010315valor es.Unless interoperating with a specification which requires the use of a different value, we recommend that you use the default .NET canonicalization method, which is the XML-C14N 1.0 algorithm, whose value is http://www.w3.org/TR/2001/REC-xml-c14n-20010315. El algoritmo XML-C14N 1,0 debe ser compatible con todas las implementaciones de XMLDSIG, especialmente como es una transformación final implícita que se va a aplicar.The XML-C14N 1.0 algorithm is required to be supported by all implementations of XMLDSIG, particularly as it is an implicit final transform to apply.

Existen versiones de algoritmos de canonización que permiten conservar los comentarios.There are versions of canonicalization algorithms which support preserving comments. No se recomiendan los métodos de canonización de preservación de comentarios porque infringen el principio "firmar lo que se ha encontrado".Comment-preserving canonicalization methods are not recommended because they violate the "sign what is seen" principle. Es decir, los comentarios de un <Signature> elemento no modificarán la lógica de procesamiento de la forma en que se realiza la firma, solo el valor de la firma.That is, the comments in a <Signature> element will not alter the processing logic for how the signature is performed, merely what the signature value is. Cuando se combina con un algoritmo de firma débil, al permitir que se incluyan los comentarios, el atacante no necesita libertad para forzar una colisión de hash, de modo que un documento alterado parezca legítimo.When combined with a weak signature algorithm, allowing the comments to be included gives an attacker unnecessary freedom to force a hash collision, making a tampered document appear legitimate. En el .NET Framework, solo se admiten canonicalizers integradas de forma predeterminada.In the .NET Framework, only built-in canonicalizers are supported by default. Para admitir canonicalizers adicionales o personalizados, vea la SafeCanonicalizationMethods propiedad.To support additional or custom canonicalizers, see the SafeCanonicalizationMethods property. Si el documento utiliza un método de canonización que no está en la colección representada por la SafeCanonicalizationMethods propiedad, el CheckSignature método falsedevolverá.If the document uses a canonicalization method that is not in the collection represented by the SafeCanonicalizationMethods property, then the CheckSignature method will return false.

Nota

Una aplicación extremadamente defensiva puede quitar cualquier valor que no espere que los firmantes usen de la SafeCanonicalizationMethods colección.An extremely defensive application can remove any values it does not expect signers to use from the SafeCanonicalizationMethods collection.

¿Son seguros los valores de referencia de la manipulación?Are the Reference values safe from tampering?

Sí, los <Reference> valores son seguros contra la manipulación.Yes, the <Reference> values are safe from tampering. .Net comprueba el <SignatureValue> cálculo antes de procesar cualquiera de los <Reference> valores y sus transformaciones asociadas, y se anulará pronto para evitar instrucciones de procesamiento potencialmente malintencionadas..NET verifies the <SignatureValue> computation before processing any of the <Reference> values and their associated transforms, and will abort early to avoid potentially malicious processing instructions.

Elección de los elementos que se van a firmarChoosing the elements to sign

Se recomienda usar el valor de "" para el URI atributo (o establecer la Uri propiedad en una cadena vacía), si es posible.We recommend that you use the value of "" for the URI attribute (or set the Uri property to an empty string), if possible. Esto significa que todo el documento se considera para el cálculo de síntesis, lo que significa que todo el documento está protegido contra alteraciones.This means the whole document is considered for the digest computation, which means the whole document is protected from tampering.

Es muy común ver URI los valores en forma de delimitadores como #foo, haciendo referencia a un elemento cuyo atributo id es "foo".It is very common to see URI values in the form of anchors such as #foo, referring to an element whose ID attribute is "foo". Desafortunadamente, es fácil manipular esto, ya que solo incluye el contenido del elemento de destino, no el contexto.Unfortunately, it is easy for this to be tampered with because this includes only the content of the target element, not the context. Desaprovechar esta distinción se denomina encapsulado de firma XML (XSW).Abusing this distinction is known as XML Signature Wrapping (XSW).

Si la aplicación considera que los comentarios son semánticos (lo que no es común al tratar con XML), debe usar "#xpointer (/)" en lugar de "" y "#xpointer (ID (' foo '))" en lugar de "#foo".If your application considers comments to be semantic (which is not common when dealing with XML), then you should use "#xpointer(/)" instead of "", and "#xpointer(id('foo'))" instead of "#foo". Las versiones #xpointer se interpretan como comentarios, mientras que los formularios de ShortName excluyen Comentarios.The #xpointer versions are interpreted as including comments, while the shortname forms are excluding comments.

Si necesita aceptar documentos que solo están parcialmente protegidos y desea asegurarse de que está leyendo el mismo contenido que la firma protegió, use el GetIdElement método.If you need to accept documents which are only partially protected and you want to ensure that you are reading the same content that the signature protected, use the GetIdElement method.

Consideraciones de seguridad sobre el elemento KeyInfoSecurity considerations about the KeyInfo element

Los datos del elemento opcional <KeyInfo> (es decir, la KeyInfo propiedad), que contiene una clave para validar la firma, no deben ser de confianza.The data in the optional <KeyInfo> element (that is, the KeyInfo property), which contains a key to validate the signature, should not be trusted.

En concreto, cuando el KeyInfo valor representa una clave pública RSA, DSA o ECDSA, el documento podría haberse alterado, a pesar de que el CheckSignature método indica que la firma es válida.In particular, when the KeyInfo value represents a bare RSA, DSA or ECDSA public key, the document could have been tampered with, despite the CheckSignature method reporting that the signature is valid. Esto puede ocurrir porque la entidad que realiza la alteración solo tiene que generar una nueva clave y volver a firmar el documento alterado con esa nueva clave.This can happen because the entity doing the tampering just has to generate a new key and re-sign the tampered document with that new key. Por lo tanto, a menos que la aplicación Compruebe que la clave pública es un valor esperado, el documento se debe tratar como si se hubiera alterado.So, unless your application verifies that the public key is an expected value, the document should be treated as if it were tampered with. Para ello, la aplicación debe examinar la clave pública incrustada en el documento y comprobarla con respecto a una lista de valores conocidos para el contexto del documento.This requires that your application examine the public key embedded within the document and verify it against a list of known values for the document context. Por ejemplo, si el documento se puede entender como emitido por un usuario conocido, debe comprobar la clave en una lista de claves conocidas utilizadas por ese usuario.For example, if the document could be understood to be issued by a known user, you'd check the key against a list of known keys used by that user.

También puede comprobar la clave después de procesar el documento mediante el CheckSignatureReturningKey método, en lugar de utilizar el CheckSignature método.You can also verify the key after processing the document by using the CheckSignatureReturningKey method, instead of using the CheckSignature method. Sin embargo, para lograr una seguridad óptima, debe comprobar la clave de antemano.But, for the optimal security, you should verify the key beforehand.

Como alternativa, considere la posibilidad de probar las claves públicas registradas del usuario, en lugar de <KeyInfo> leer lo que hay en el elemento.Alternately, consider trying the user's registered public keys, rather than reading what's in the <KeyInfo> element.

Consideraciones de seguridad sobre el elemento X509DataSecurity considerations about the X509Data element

El elemento <X509Data> opcional es un elemento secundario del <KeyInfo> elemento y contiene uno o más certificados X509 o identificadores para los certificados X509.The optional <X509Data> element is a child of the <KeyInfo> element and contains one or more X509 certificates or identifiers for X509 certificates. Los datos del <X509Data> elemento tampoco deben ser de confianza inherente.The data in the <X509Data> element should also not be inherently trusted.

Al comprobar un documento con el elemento incrustado <X509Data> , .net solo comprueba que los datos se resuelven en un certificado X509 cuya clave pública se puede usar correctamente para validar la firma del documento.When verifying a document with the embedded <X509Data> element, .NET verifies only that the data resolves to an X509 certificate whose public key can be successfully used to validate the document signature. A diferencia de la CheckSignature llamada al método verifySignatureOnly con el parámetro falseestablecido en, no se realiza ninguna comprobación de revocación, no se comprueba ninguna confianza de cadena y no se comprueba la expiración.Unlike calling the CheckSignature method with the verifySignatureOnly parameter set to false, no revocation check is performed, no chain trust is checked, and no expiration is verified. Incluso si la aplicación extrae el certificado y lo pasa al CheckSignature método con el verifySignatureOnly parámetro establecido en false, todavía no hay validación suficiente para evitar la manipulación del documento.Even if your application extracts the certificate itself and passes it to the CheckSignature method with the verifySignatureOnly parameter set to false, that is still not sufficient validation to prevent document tampering. Todavía es necesario comprobar el certificado como apropiado para el documento que se está firmando.The certificate still needs to be verified as being appropriate for the document being signed.

El uso de un certificado de firma incrustado puede proporcionar estrategias de rotación de <X509Data> claves útiles, ya sea en la sección o en el contenido del documento.Using an embedded signing certificate can provide useful key rotation strategies, whether in the <X509Data> section or in the document content. Cuando se usa este enfoque, una aplicación debe extraer el certificado manualmente y realizar una validación similar a la siguiente:When using this approach an application should extract the certificate manually and perform validation similar to:

  • El certificado se emitió directamente o a través de una cadena de una entidad de certificación (CA) cuyo certificado público se incrusta en la aplicación.The certificate was issued directly or via a chain by a Certificate Authority (CA) whose public certificate is embedded in the application.

    El uso de la lista de confianza proporcionada por el sistema operativo sin comprobaciones adicionales, como un nombre de sujeto conocido, no es SignedXmlsuficiente para evitar alteraciones.Using the OS-provided trust list without additional checks, such as a known subject name, is not sufficient to prevent tampering in SignedXml.

  • Se comprueba que el certificado no ha expirado en el momento de la firma del documento (o "ahora" para el procesamiento de documentos casi en tiempo real).The certificate is verified to have not been expired at the time of document signing (or "now" for near real-time document processing).

  • En el caso de los certificados de larga duración emitidos por una CA que admite la revocación, compruebe que el certificado no se ha revocado.For long-lived certificates issued by a CA which supports revocation, verify the certificate was not revoked.

  • Se comprueba que el sujeto del certificado es adecuado para el documento actual.The certificate subject is verified as being appropriate to the current document.

Elección del algoritmo de transformaciónChoosing the transform algorithm

Si está interoperando con una especificación que ha dictado valores específicos (como XrML), debe seguir la especificación.If you are interoperating with a specification which has dictated specific values (such as XrML), then you need to follow the specification. Si tiene una firma con doble cifrado (por ejemplo, al firmar todo el documento), debe usar http://www.w3.org/2000/09/xmldsig#enveloped-signature (representado por la XmlDsigEnvelopedSignatureTransform clase).If you have an enveloped signature (such as when signing the whole document), then you need to use http://www.w3.org/2000/09/xmldsig#enveloped-signature (represented by the XmlDsigEnvelopedSignatureTransform class). También puede especificar la transformación XML-C14N implícita, pero no es necesario.You can specify the implicit XML-C14N transform as well, but it's not necessary. En el caso de una firma de envoltura o desasociada, no se requieren transformaciones.For an enveloping or detached signature, no transforms are required. La transformación XML-C14N implícita se encarga de todo.The implicit XML-C14N transform takes care of everything.

Con la seguridad actualizada introducida por el boletín de seguridad de Microsoft MS16-035, .net ha restringido las transformaciones que se pueden usar en la comprobación de documentos de forma predeterminada, CheckSignature con transformaciones que no son de confianza, lo que provoca que siempre devuelva. falseWith the security updated introduced by the Microsoft Security Bulletin MS16-035, .NET has restricted what transforms can be used in document verification by default, with untrusted transforms causing CheckSignature to always return false. En concreto, las transformaciones que requieren una entrada adicional (especificadas como elementos secundarios en el XML) ya no se permiten debido a su susceptibilidad de abuso por parte de usuarios malintencionados.In particular, transforms which require additional input (specified as child elements in the XML) are no longer allowed due to their susceptibility of abuse by malicious users. El W3C aconseja evitar las transformaciones XPath y XSLT, que son las dos transformaciones principales afectadas por estas restricciones.The W3C advises avoiding the XPath and XSLT transforms, which are the two main transforms affected by these restrictions.

El problema con las referencias externasThe problem with external references

Si una aplicación no comprueba que las referencias externas parezcan adecuadas para el contexto actual, se pueden abusar de maneras que proporcionen muchas vulnerabilidades de seguridad (incluida la denegación de servicio, la denegación de servicio de la reflexión distribuida y la información Divulgación, omisión de la firma y ejecución remota de código).If an application does not verify that external references seem appropriate for the current context, they can be abused in ways that provide for many security vulnerabilities (including Denial of Service, Distributed Reflection Denial of Service, Information Disclosure, Signature Bypass, and Remote Code Execution). Incluso si una aplicación validara el URI de referencia externa, se seguiría un problema del recurso que se estaba cargando dos veces: una vez cuando la aplicación lo lee y SignedXml otra cuando lo lee.Even if an application were to validate the external reference URI, there would remain a problem of the resource being loaded twice: once when your application reads it, and once when SignedXml reads it. Dado que no hay ninguna garantía de que los pasos de lectura y comprobación de documentos de la aplicación tengan el mismo contenido, la firma no proporciona confiabilidad.Since there's no guarantee that the application read and document verify steps have the same content, the signature does not provide trustworthiness.

Dados los riesgos de las referencias externas SignedXml , producirá una excepción cuando se encuentre una referencia externa.Given the risks of external references, SignedXml will throw an exception when an external reference is encountered. Para obtener más información acerca de este problema, consulte el artículo 3148821 de Knowledge Base.For more information about this issue, see KB article 3148821.

Constructores

SignedXml()

Inicializa una nueva instancia de la clase SignedXml.Initializes a new instance of the SignedXml class.

SignedXml(XmlDocument)

Inicializa una nueva instancia de la clase SignedXml a partir del documento XML especificado.Initializes a new instance of the SignedXml class from the specified XML document.

SignedXml(XmlElement)

Inicializa una nueva instancia de la clase SignedXml a partir del objeto XmlElement especificado.Initializes a new instance of the SignedXml class from the specified XmlElement object.

Campos

m_signature

Representa el objeto Signature del objeto SignedXml actual.Represents the Signature object of the current SignedXml object.

m_strSigningKeyName

Representa el nombre de la clave instalada que se va a utilizar para firmar el objeto SignedXml.Represents the name of the installed key to be used for signing the SignedXml object.

XmlDecryptionTransformUrl

Representa el identificador uniforme de recursos (URI) para la transformación de descifrado de modo XML.Represents the Uniform Resource Identifier (URI) for the XML mode decryption transformation. Este campo es constante.This field is constant.

XmlDsigBase64TransformUrl

Representa el identificador uniforme de recursos (URI) para la transformación de base 64.Represents the Uniform Resource Identifier (URI) for the base 64 transformation. Este campo es constante.This field is constant.

XmlDsigC14NTransformUrl

Representa el identificador uniforme de recursos (URI) para la transformación de XML canónico.Represents the Uniform Resource Identifier (URI) for the Canonical XML transformation. Este campo es constante.This field is constant.

XmlDsigC14NWithCommentsTransformUrl

Representa el identificador uniforme de recursos (URI) para la transformación de XML canónico, con comentarios.Represents the Uniform Resource Identifier (URI) for the Canonical XML transformation, with comments. Este campo es constante.This field is constant.

XmlDsigCanonicalizationUrl

Representa el identificador uniforme de recursos (URI) del algoritmo de canonización estándar para las firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard canonicalization algorithm for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigCanonicalizationWithCommentsUrl

Representa el identificador uniforme de recursos (URI) del algoritmo de canonización estándar para las firmas digitales XML e incluye comentarios.Represents the Uniform Resource Identifier (URI) for the standard canonicalization algorithm for XML digital signatures and includes comments. Este campo es constante.This field is constant.

XmlDsigDSAUrl

Representa el identificador uniforme de recursos (URI) del algoritmo DSA estándar para las firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard DSA algorithm for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigEnvelopedSignatureTransformUrl

Representa el identificador uniforme de recursos (URI) para la transformación de firma con doble cifrado.Represents the Uniform Resource Identifier (URI) for enveloped signature transformation. Este campo es constante.This field is constant.

XmlDsigExcC14NTransformUrl

Representa el identificador uniforme de recursos (URI) para la canonización XML exclusiva.Represents the Uniform Resource Identifier (URI) for exclusive XML canonicalization. Este campo es constante.This field is constant.

XmlDsigExcC14NWithCommentsTransformUrl

Representa el identificador uniforme de recursos (URI) para la canonización XML exclusiva, con comentarios.Represents the Uniform Resource Identifier (URI) for exclusive XML canonicalization, with comments. Este campo es constante.This field is constant.

XmlDsigHMACSHA1Url

Representa el identificador uniforme de recursos (URI) del algoritmo HMACSHA1 estándar para las firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard HMACSHA1 algorithm for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigMinimalCanonicalizationUrl

Representa el identificador uniforme de recursos (URI) del algoritmo de canonización mínima estándar para las firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard minimal canonicalization algorithm for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigNamespaceUrl

Representa el identificador uniforme de recursos (URI) del espacio de nombres estándar para las firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard namespace for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigRSASHA1Url

Representa el identificador uniforme de recursos (URI) del método de firma RSA estándar para las firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard RSA signature method for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigRSASHA256Url

Representa el identificador uniforme de recursos (URI) para la variación de método de firma SHA-256 RSA para firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the RSA SHA-256 signature method variation for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigRSASHA384Url

Representa el identificador uniforme de recursos (URI) para la variación de método de firma SHA-384 RSA para firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the RSA SHA-384 signature method variation for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigRSASHA512Url

Representa el identificador uniforme de recursos (URI) para la variación de método de firma SHA-512 RSA para firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the RSA SHA-512 signature method variation for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigSHA1Url

Representa el identificador uniforme de recursos (URI) para el método implícito estándar SHA1 para firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard SHA1 digest method for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigSHA256Url

Representa el identificador uniforme de recursos (URI) para el método implícito estándar SHA256 para firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard SHA256 digest method for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigSHA384Url

Representa el identificador uniforme de recursos (URI) para el método implícito estándar SHA384 para firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard SHA384 digest method for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigSHA512Url

Representa el identificador uniforme de recursos (URI) para el método implícito estándar SHA512 para firmas digitales XML.Represents the Uniform Resource Identifier (URI) for the standard SHA512 digest method for XML digital signatures. Este campo es constante.This field is constant.

XmlDsigXPathTransformUrl

Representa el identificador uniforme de recursos (URI) para XPath (lenguaje de rutas XML).Represents the Uniform Resource Identifier (URI) for the XML Path Language (XPath). Este campo es constante.This field is constant.

XmlDsigXsltTransformUrl

Representa el identificador uniforme de recursos (URI) para las transformaciones XSLT.Represents the Uniform Resource Identifier (URI) for XSLT transformations. Este campo es constante.This field is constant.

XmlLicenseTransformUrl

Representa el identificador uniforme de recursos (URI) del algoritmo de transformación de licencias utilizado para normalizar licencias XrML para firmas.Represents the Uniform Resource Identifier (URI) for the license transform algorithm used to normalize XrML licenses for signatures.

Propiedades

EncryptedXml

Obtiene o establece un objeto EncryptedXml que define las reglas de procesamiento del cifrado XML.Gets or sets an EncryptedXml object that defines the XML encryption processing rules.

KeyInfo

Obtiene o establece el objeto KeyInfo del objeto SignedXml actual.Gets or sets the KeyInfo object of the current SignedXml object.

Resolver

Establece el objeto XmlResolver actual.Sets the current XmlResolver object.

SafeCanonicalizationMethods

Obtiene los nombres de los métodos cuyos algoritmos de nombres canónicos se permiten de forma explícita.Gets the names of methods whose canonicalization algorithms are explicitly allowed.

Signature

Obtiene el objeto Signature del objeto SignedXml actual.Gets the Signature object of the current SignedXml object.

SignatureFormatValidator

Obtiene un delegado al que se va a llamar para validar el formato (no la seguridad criptográfica) de una signatura XML.Gets a delegate that will be called to validate the format (not the cryptographic security) of an XML signature.

SignatureLength

Obtiene la longitud de la firma para el objeto SignedXml actual.Gets the length of the signature for the current SignedXml object.

SignatureMethod

Obtiene el método de firma del objeto SignedXml actual.Gets the signature method of the current SignedXml object.

SignatureValue

Obtiene el valor de firma del objeto SignedXml actual.Gets the signature value of the current SignedXml object.

SignedInfo

Obtiene el objeto SignedInfo del objeto SignedXml actual.Gets the SignedInfo object of the current SignedXml object.

SigningKey

Obtiene o establece la clave del algoritmo asimétrico que se utiliza para la firma de un objeto SignedXml.Gets or sets the asymmetric algorithm key used for signing a SignedXml object.

SigningKeyName

Obtiene o establece el nombre de la clave instalada que se va a utilizar para firmar el objeto SignedXml.Gets or sets the name of the installed key to be used for signing the SignedXml object.

Métodos

AddObject(DataObject)

Agrega un objeto DataObject a la lista de objetos que se van a firmar.Adds a DataObject object to the list of objects to be signed.

AddReference(Reference)

Agrega un objeto Reference al objeto SignedXml, que describe un método de síntesis, valor de síntesis y transformación que se utilizan para crear una firma digital XML.Adds a Reference object to the SignedXml object that describes a digest method, digest value, and transform to use for creating an XML digital signature.

CheckSignature()

Determina si la propiedad Signature realiza una comprobación utilizando la clave pública de la firma.Determines whether the Signature property verifies using the public key in the signature.

CheckSignature(AsymmetricAlgorithm)

Determina si la propiedad Signature realiza una comprobación para la clave especificada.Determines whether the Signature property verifies for the specified key.

CheckSignature(KeyedHashAlgorithm)

Determina si la propiedad Signature comprueba el algoritmo de código de autenticación de mensajes (MAC) especificado.Determines whether the Signature property verifies for the specified message authentication code (MAC) algorithm.

CheckSignature(X509Certificate2, Boolean)

Determina si la propiedad Signature realiza una comprobación del objeto X509Certificate2 especificado y, opcionalmente, si el certificado es válido.Determines whether the Signature property verifies for the specified X509Certificate2 object and, optionally, whether the certificate is valid.

CheckSignatureReturningKey(AsymmetricAlgorithm)

Determina si la propiedad Signature realiza una comprobación utilizando la clave pública de la firma.Determines whether the Signature property verifies using the public key in the signature.

ComputeSignature()

Calcula una firma digital XML.Computes an XML digital signature.

ComputeSignature(KeyedHashAlgorithm)

Calcula una firma digital XML utilizando el algoritmo de código de autenticación de mensajes (MAC) especificado.Computes an XML digital signature using the specified message authentication code (MAC) algorithm.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Heredado de Object)
GetHashCode()

Sirve como función hash predeterminada.Serves as the default hash function.

(Heredado de Object)
GetIdElement(XmlDocument, String)

Devuelve el objeto XmlElement con el identificador del objeto XmlDocument especificado.Returns the XmlElement object with the specified ID from the specified XmlDocument object.

GetPublicKey()

Devuelve la clave pública de una firma.Returns the public key of a signature.

GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
GetXml()

Devuelve la representación XML de un objeto SignedXml.Returns the XML representation of a SignedXml object.

LoadXml(XmlElement)

Carga un estado de la clase SignedXml a partir de un elemento XML.Loads a SignedXml state from an XML element.

MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
ToString()

Devuelve un valor de tipo string que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)

Se aplica a

Consulte también: