SignedXml Class

Definition

Provides a wrapper on a core XML signature object to facilitate creating XML signatures.

public class SignedXml
Inheritance
SignedXml

Inherited Members

System.Object

Examples

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

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

Remarks

The SignedXml class is the .NET Framework implementation of the World Wide Web Consortium (W3C) XML Signature Syntax and Processing Specification, also known as XMLDSIG (XML Digital Signature). 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).

Use the SignedXml class whenever you need to share signed XML data between applications or organizations in a standard way. Any data signed using this class can be verified by any conforming implementation of the W3C specification for XMLDSIG.

The SignedXml class allows you to create the following three kinds of XML digital signatures:

Signature Type Description
Enveloped signature The signature is contained within the XML element being signed.
Enveloping signature The signed XML is contained within the <Signature> element.
Internal detached signature The signature and signed XML are in the same document, but neither element contains the other.

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. External detached signatures are not supported by the SignedXml class.

The structure of an XML Signature

XMLDSIG creates a <Signature> element, which contains a digital signature of an XML document or other data that is addressable from a URI. 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. 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>  

The main parts of this structure are:

The <CanonicalizationMethod> element
Specifies the rules for rewriting the Signature element from XML/text into bytes for signature validation. The default value in the .NET Framework is http://www.w3.org/TR/2001/REC-xml-c14n-20010315, which identifies a trustworthy algorithm. This element is represented by the SignedInfo.CanonicalizationMethod property.

The <SignatureMethod> element
Specifies the algorithm used for signature generation and validation, which was applied to the <Signature> element to produce the value in <SignatureValue>. In the example above, the value http://www.w3.org/2000/09/xmldsig#rsa-sha1 identifies an RSA PKCS1 SHA-1 signature. This element is represented by the SignatureMethod property.

The <SignatureValue> element
Specifies the cryptographic signature for the <Signature> element. If this signature does not verify, then some portion of the <Signature> block was tampered with, and the document is considered invalid. As long as the <CanonicalizationMethod> value is trustworthy, this value is highly resistant to tampering. This element is represented by the SignatureValue property.

The URI attribute of the <Reference> element
Specifies a data object using a URI reference. This attribute is represented by the Reference.Uri property.

  • 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. In most cases, a null URI will result in an exception being thrown. Do not use a null URI, unless your application is interoperating with a protocol which requires it.

  • Setting the URI attribute to an empty string indicates that the root element of the document is being signed, a form of enveloped signature.

  • If the value of URI attribute starts with #, then the value must resolve to an element in the current document. This form can be used with any of the supported signature types (enveloped signature, enveloping signature or internal detached signature).

  • Anything else is considered an external resource detached signature and is not supported by the SignedXml class.

The <Transforms> element
Contains an ordered list of <Transform> elements that describe how the signer obtained the data object that was digested. 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. The <Transforms> element is represented by the TransformChain class.

  • Each transform algorithm is defined as taking either XML (an XPath node-set) or bytes as input. If the format of the current data differs from the transform input requirements, conversion rules are applied.

  • Each transform algorithm is defined as producing either XML or bytes as the output.

  • If the output of the last transform algorithm is not defined in bytes (or no transforms were specified), then the canonicalization method http://www.w3.org/TR/2001/REC-xml-c14n-20010315 is used as an implicit transform (even if a different algorithm was specified in the <CanonicalizationMethod> element).

  • 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. 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.

The <DigestMethod> element
Identifies the digest (cryptographic hash) method to apply on the transformed content identified by the URI attribute of the <Reference> element. This is represented by the Reference.DigestMethod property.

Choosing a canonicalization method

Unless interoperating with a specification which requires the use of a different value, we recommend that you use the default canonicalization method in the .NET Framework which is the XML-C14N 1.0 algorithm, whose value is http://www.w3.org/TR/2001/REC-xml-c14n-20010315. 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.

There are versions of canonicalization algorithms which support preserving comments. Comment-preserving canonicalization methods are not recommended because they violate the "sign what is seen" principle. 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. 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. In the .NET Framework, only built-in canonicalizers are supported by default. To support additional or custom canonicalizers, see the SafeCanonicalizationMethods property. 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.

Note

An extremely defensive application can remove any values it does not expect signers to use from the SafeCanonicalizationMethods collection.

Are the Reference values safe from tampering?

Yes, the <Reference> values are safe from tampering. The .NET framework 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.

Choosing the elements to sign

We recommend that you use the value of "" for the URI attribute (or set the Uri property to an empty string), if possible. This means the whole document is considered for the digest computation, which means the whole document is protected from tampering.

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". Unfortunately, it is easy for this to be tampered with because this includes only the content of the target element, not the context. Abusing this distinction is known as XML Signature Wrapping (XSW).

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". The #xpointer versions are interpreted as including comments, while the shortname forms are excluding comments.

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.

Security considerations about the KeyInfo element

The data in the optional <KeyInfo> element (that is, the KeyInfo property), which contains a key to validate the signature, should not be trusted.

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. 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. So, unless your application verifies that the public key is an expected value, the document should be treated as if it were tampered with. 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. 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.

You can also verify the key after processing the document by using the CheckSignatureReturningKey method, instead of using the CheckSignature method. But, for the optimal security, you should verify the key beforehand.

Alternately, consider trying the user's registered public keys, rather than reading what's in the <KeyInfo> element.

Security considerations about the X509Data element

The optional <X509Data> element is a child of the <KeyInfo> element and contains one or more X509 certificates or identifiers for X509 certificates. The data in the <X509Data> element should also not be inherently trusted.

When verifying a document with the embedded <X509Data> element, the .NET Framework verifies only that the data resolves to an X509 certificate whose public key can be successfully used to validate the document signature. 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. 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. The certificate still needs to be verified as being appropriate for the document being signed.

Using an embedded signing certificate can provide useful key rotation strategies, whether in the <X509Data> section or in the document content. When using this approach an application should extract the certificate manually and perform validation similar to:

  • The certificate was issued directly or via a chain by a Certificate Authority (CA) whose public certificate is embedded in the application.

    Using the OS-provided trust list without additional checks, such as a known subject name, is not sufficient to prevent tampering in SignedXml.

  • The certificate is verified to have not been expired at the time of document signing (or "now" for near real-time document processing).

  • For long-lived certificates issued by a CA which supports revocation, verify the certificate was not revoked.

  • The certificate subject is verified as being appropriate to the current document.

Choosing the transform algorithm

If you are interoperating with a specification which has dictated specific values (such as XrML), then you need to follow the specification. 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). You can specify the implicit XML-C14N transform as well, but it's not necessary. For an enveloping or detached signature, no transforms are required. The implicit XML-C14N transform takes care of everything.

With the security updated introduced by the Microsoft Security Bulletin MS16-035, the .NET Framework has restricted what transforms can be used in document verification by default, with untrusted transforms causing CheckSignature to always return false. 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. The W3C advises avoiding the XPath and XSLT transforms, which are the two main transforms affected by these restrictions.

The problem with external references

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). 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. Since there’s no guarantee that the application read and document verify steps have the same content, the signature does not provide trustworthiness.

Given the risks of external references, SignedXml will throw an exception when an external reference is encountered. For more information about this issue, see KB article 3148821.

Constructors

SignedXml()

Initializes a new instance of the SignedXml class.

SignedXml(XmlDocument)

Initializes a new instance of the SignedXml class from the specified XML document.

SignedXml(XmlElement)

Initializes a new instance of the SignedXml class from the specified XmlElement object.

Fields

m_signature

Represents the Signature object of the current SignedXml object.

m_strSigningKeyName

Represents the name of the installed key to be used for signing the SignedXml object.

XmlDecryptionTransformUrl

Represents the Uniform Resource Identifier (URI) for the XML mode decryption transformation. This field is constant.

XmlDsigBase64TransformUrl

Represents the Uniform Resource Identifier (URI) for the base 64 transformation. This field is constant.

XmlDsigC14NTransformUrl

Represents the Uniform Resource Identifier (URI) for the Canonical XML transformation. This field is constant.

XmlDsigC14NWithCommentsTransformUrl

Represents the Uniform Resource Identifier (URI) for the Canonical XML transformation, with comments. This field is constant.

XmlDsigCanonicalizationUrl

Represents the Uniform Resource Identifier (URI) for the standard canonicalization algorithm for XML digital signatures. This field is constant.

XmlDsigCanonicalizationWithCommentsUrl

Represents the Uniform Resource Identifier (URI) for the standard canonicalization algorithm for XML digital signatures and includes comments. This field is constant.

XmlDsigDSAUrl

Represents the Uniform Resource Identifier (URI) for the standard DSA algorithm for XML digital signatures. This field is constant.

XmlDsigEnvelopedSignatureTransformUrl

Represents the Uniform Resource Identifier (URI) for enveloped signature transformation. This field is constant.

XmlDsigExcC14NTransformUrl

Represents the Uniform Resource Identifier (URI) for exclusive XML canonicalization. This field is constant.

XmlDsigExcC14NWithCommentsTransformUrl

Represents the Uniform Resource Identifier (URI) for exclusive XML canonicalization, with comments. This field is constant.

XmlDsigHMACSHA1Url

Represents the Uniform Resource Identifier (URI) for the standard HMACSHA1 algorithm for XML digital signatures. This field is constant.

XmlDsigMinimalCanonicalizationUrl

Represents the Uniform Resource Identifier (URI) for the standard minimal canonicalization algorithm for XML digital signatures. This field is constant.

XmlDsigNamespaceUrl

Represents the Uniform Resource Identifier (URI) for the standard namespace for XML digital signatures. This field is constant.

XmlDsigRSASHA1Url

Represents the Uniform Resource Identifier (URI) for the standard RSA signature method for XML digital signatures. This field is constant.

XmlDsigRSASHA256Url

Represents the Uniform Resource Identifier (URI) for the RSA SHA-256 signature method variation for XML digital signatures. This field is constant.

XmlDsigRSASHA384Url

Represents the Uniform Resource Identifier (URI) for the RSA SHA-384 signature method variation for XML digital signatures. This field is constant.

XmlDsigRSASHA512Url

Represents the Uniform Resource Identifier (URI) for the RSA SHA-512 signature method variation for XML digital signatures. This field is constant.

XmlDsigSHA1Url

Represents the Uniform Resource Identifier (URI) for the standard SHA1 digest method for XML digital signatures. This field is constant.

XmlDsigSHA256Url

Represents the Uniform Resource Identifier (URI) for the standard SHA256 digest method for XML digital signatures. This field is constant.

XmlDsigSHA384Url

Represents the Uniform Resource Identifier (URI) for the standard SHA384 digest method for XML digital signatures. This field is constant.

XmlDsigSHA512Url

Represents the Uniform Resource Identifier (URI) for the standard SHA512 digest method for XML digital signatures. This field is constant.

XmlDsigXPathTransformUrl

Represents the Uniform Resource Identifier (URI) for the XML Path Language (XPath). This field is constant.

XmlDsigXsltTransformUrl

Represents the Uniform Resource Identifier (URI) for XSLT transformations. This field is constant.

XmlLicenseTransformUrl

Represents the Uniform Resource Identifier (URI) for the license transform algorithm used to normalize XrML licenses for signatures.

Properties

EncryptedXml

Gets or sets an EncryptedXml object that defines the XML encryption processing rules.

KeyInfo

Gets or sets the KeyInfo object of the current SignedXml object.

Resolver

Sets the current XmlResolver object.

SafeCanonicalizationMethods

[Supported in the .NET Framework 4.5.1 and later versions]

Gets the names of methods whose canonicalization algorithms are explicitly allowed.

Signature

Gets the Signature object of the current SignedXml object.

SignatureFormatValidator

Gets a delegate that will be called to validate the format (not the cryptographic security) of an XML signature.

SignatureLength

Gets the length of the signature for the current SignedXml object.

SignatureMethod

Gets the signature method of the current SignedXml object.

SignatureValue

Gets the signature value of the current SignedXml object.

SignedInfo

Gets the SignedInfo object of the current SignedXml object.

SigningKey

Gets or sets the asymmetric algorithm key used for signing a SignedXml object.

SigningKeyName

Gets or sets the name of the installed key to be used for signing the SignedXml object.

Methods

AddObject(DataObject)

Adds a DataObject object to the list of objects to be signed.

AddReference(Reference)

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

Determines whether the Signature property verifies using the public key in the signature.

CheckSignature(AsymmetricAlgorithm)

Determines whether the Signature property verifies for the specified key.

CheckSignature(KeyedHashAlgorithm)

Determines whether the Signature property verifies for the specified message authentication code (MAC) algorithm.

CheckSignature(X509Certificate2, Boolean)

Determines whether the Signature property verifies for the specified X509Certificate2 object and, optionally, whether the certificate is valid.

CheckSignatureReturningKey(AsymmetricAlgorithm)

Determines whether the Signature property verifies using the public key in the signature.

ComputeSignature()

Computes an XML digital signature.

ComputeSignature(KeyedHashAlgorithm)

Computes an XML digital signature using the specified message authentication code (MAC) algorithm.

GetIdElement(XmlDocument, String)

Returns the XmlElement object with the specified ID from the specified XmlDocument object.

GetPublicKey()

Returns the public key of a signature.

GetXml()

Returns the XML representation of a SignedXml object.

LoadXml(XmlElement)

Loads a SignedXml state from an XML element.