.NET Framework Class Library
SignedXml Class

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

Inheritance Hierarchy
SystemObject
  System.Security.Cryptography.XmlSignedXml

Namespace:   System.Security.Cryptography.Xml
Assembly:  System.Security (in System.Security.dll)
Syntax
<[%$TOPIC/3y0fth1d_en-us_VS_110_2_0_0_0_0%]([%$TOPIC/3y0fth1d_en-us_VS_110_2_0_0_0_1%].LinkDemand, MayLeakOnAbort := True)> _
Public Class SignedXml
[[%$TOPIC/3y0fth1d_en-us_VS_110_2_0_1_0_0%]([%$TOPIC/3y0fth1d_en-us_VS_110_2_0_1_0_1%].LinkDemand, MayLeakOnAbort = true)]
public class SignedXml
[[%$TOPIC/3y0fth1d_en-us_VS_110_2_0_2_0_0%]([%$TOPIC/3y0fth1d_en-us_VS_110_2_0_2_0_1%]::LinkDemand, MayLeakOnAbort = true)]
public ref class SignedXml
[<[%$TOPIC/3y0fth1d_en-us_VS_110_2_0_3_0_0%]([%$TOPIC/3y0fth1d_en-us_VS_110_2_0_3_0_1%].LinkDemand, MayLeakOnAbort = true)>]
type SignedXml =  class end

The SignedXml type exposes the following members.

Constructors
  NameDescription
Public method SignedXmlInitializes a new instance of the SignedXml class.
Public method SignedXml(XmlDocument)Initializes a new instance of the SignedXml class from the specified XML document.
Public method SignedXml(XmlElement)Initializes a new instance of the SignedXml class from the specified XmlElement object.
Top
Properties
  NameDescription
Public property EncryptedXmlGets or sets an EncryptedXml object that defines the XML encryption processing rules.
Public property KeyInfoGets or sets the KeyInfo object of the current SignedXml object.
Public property ResolverSets the current XmlResolver object.
Public property SignatureGets the Signature object of the current SignedXml object.
Public property SignatureFormatValidatorGets a delegate that will be called to validate the format (not the cryptographic security) of an XML signature.
Public property SignatureLengthGets the length of the signature for the current SignedXml object.
Public property SignatureMethodGets the signature method of the current SignedXml object.
Public property SignatureValueGets the signature value of the current SignedXml object.
Public property SignedInfoGets the SignedInfo object of the current SignedXml object.
Public property SigningKeyGets or sets the asymmetric algorithm key used for signing a SignedXml object.
Public property SigningKeyNameInfrastructure. Gets or sets the name of the installed key to be used for signing the SignedXml object.
Top
Methods
  NameDescription
Public method AddObjectAdds a DataObject object to the list of objects to be signed.
Public method AddReferenceAdds a Reference object to the SignedXml object that describes a digest method, digest value, and transform to use for creating an XML digital signature.
Public method CheckSignatureDetermines whether the Signature property verifies using the public key in the signature.
Public method CheckSignature(AsymmetricAlgorithm)Determines whether the Signature property verifies for the specified key.
Public method CheckSignature(KeyedHashAlgorithm)Determines whether the Signature property verifies for the specified message authentication code (MAC) algorithm.
Public method CheckSignature(X509Certificate2, Boolean)Determines whether the Signature property verifies for the specified X509Certificate2 object and, optionally, whether the certificate is valid.
Public method CheckSignatureReturningKeyDetermines whether the Signature property verifies using the public key in the signature.
Public method ComputeSignatureComputes an XML digital signature.
Public method ComputeSignature(KeyedHashAlgorithm)Computes an XML digital signature using the specified message authentication code (MAC) algorithm.
Public method Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method GetIdElementReturns the XmlElement object with the specified ID from the specified XmlDocument object.
Protected method GetPublicKeyReturns the public key of a signature.
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method GetXmlReturns the XML representation of a SignedXml object.
Public method LoadXmlLoads a SignedXml state from an XML element.
Protected method MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public method ToStringReturns a string that represents the current object. (Inherited from Object.)
Top
Fields
  NameDescription
Protected field m_signatureInfrastructure. Represents the Signature object of the current SignedXml object.
Protected field m_strSigningKeyNameInfrastructure. Represents the name of the installed key to be used for signing the SignedXml object.
Public field Static member XmlDecryptionTransformUrlRepresents the Uniform Resource Identifier (URI) for the XML mode decryption transformation. This field is constant.
Public field Static member XmlDsigBase64TransformUrlRepresents the Uniform Resource Identifier (URI) for the base 64 transformation. This field is constant.
Public field Static member XmlDsigC14NTransformUrlRepresents the Uniform Resource Identifier (URI) for the Canonical XML transformation. This field is constant.
Public field Static member XmlDsigC14NWithCommentsTransformUrlRepresents the Uniform Resource Identifier (URI) for the Canonical XML transformation, with comments. This field is constant.
Public field Static member XmlDsigCanonicalizationUrlRepresents the Uniform Resource Identifier (URI) for the standard canonicalization algorithm for XML digital signatures. This field is constant.
Public field Static member XmlDsigCanonicalizationWithCommentsUrlRepresents the Uniform Resource Identifier (URI) for the standard canonicalization algorithm for XML digital signatures and includes comments. This field is constant.
Public field Static member XmlDsigDSAUrlRepresents the Uniform Resource Identifier (URI) for the standard DSA algorithm for XML digital signatures. This field is constant.
Public field Static member XmlDsigEnvelopedSignatureTransformUrlRepresents the Uniform Resource Identifier (URI) for enveloped signature transformation. This field is constant.
Public field Static member XmlDsigExcC14NTransformUrlRepresents the Uniform Resource Identifier (URI) for exclusive XML canonicalization. This field is constant.
Public field Static member XmlDsigExcC14NWithCommentsTransformUrlRepresents the Uniform Resource Identifier (URI) for exclusive XML canonicalization, with comments. This field is constant.
Public field Static member XmlDsigHMACSHA1UrlRepresents the Uniform Resource Identifier (URI) for the standard HMACSHA1 algorithm for XML digital signatures. This field is constant.
Public field Static member XmlDsigMinimalCanonicalizationUrlRepresents the Uniform Resource Identifier (URI) for the standard minimal canonicalization algorithm for XML digital signatures. This field is constant.
Public field Static member XmlDsigNamespaceUrlRepresents the Uniform Resource Identifier (URI) for the standard namespace for XML digital signatures. This field is constant.
Public field Static member XmlDsigRSASHA1UrlRepresents the Uniform Resource Identifier (URI) for the standard RSA signature method for XML digital signatures. This field is constant.
Public field Static member XmlDsigSHA1UrlRepresents the Uniform Resource Identifier (URI) for the standard SHA1 digest method for XML digital signatures. This field is constant.
Public field Static member XmlDsigXPathTransformUrlRepresents the Uniform Resource Identifier (URI) for the XML Path Language (XPath). This field is constant.
Public field Static member XmlDsigXsltTransformUrlRepresents the Uniform Resource Identifier (URI) for XSLT transformations. This field is constant.
Public field Static member XmlLicenseTransformUrlRepresents the Uniform Resource Identifier (URI) for the license transform algorithm used to normalize XrML licenses for signatures.
Top
Remarks

The SignedXml class is the main class used for XML signing and verification (XMLDSIG) in the .NET Framework. 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). The .NET Framework XMLDSIG classes implement the World Wide Web Consortium (W3C) specification for XML signing and verification located at http://www.w3.org/TR/xmldsig-core/.

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.

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 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 document being signed.

Enveloping signature

The signed XML is contained within the <Signature> element.

Detached signature

The signature is in a separate document from the data being signed.

Use one of the following methods to exchange key information:

  • Do not include any key information. If you choose this option, both parties must agree on an algorithm and key before they exchange a digital signature.

  • Include a public key in the <EncryptedKey> element.

  • Include the location of the key in the URI attribute of the <RetrievalMethod> element. Both parties must agree on the key location ahead of time and this location must be kept secret.

  • Include a string name that maps to a key in the <KeyName> element. Both parties must agree on the key name mapping before they exchange encrypted data and this mapping must be kept secret.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

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. 
' 
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
// 
// 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. 
//
#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 );
   }

}

The following code example shows how to sign and verify an object that is addressable from a Uniform Resource Identifier (URI), using a detached signature..

' 
' This example signs a file specified by a URI  
' using a detached signature. It then verifies   
' the signed XML. 
' 
Imports System
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Text
Imports System.Xml




Class XMLDSIGDetached


   <STAThread()>  _
   Overloads Shared Sub Main(args() As String)
      ' The URI to sign. 
      Dim resourceToSign As String = "http://www.microsoft.com" 

      ' The name of the file to which to save the XML signature. 
      Dim XmlFileName As String = "xmldsig.xml" 

      Try 

         ' Generate a signing key. 
         Dim Key As New RSACryptoServiceProvider()

         Console.WriteLine("Signing: {0}", resourceToSign)

         ' Sign the detached resourceand save the signature in an XML file.
         SignDetachedResource(resourceToSign, XmlFileName, Key)

         Console.WriteLine("XML Signature was succesfully computed and saved to {0}.", XmlFileName)

         ' Verify the signature of the signed XML.
         Console.WriteLine("Verifying signature...")

         'Verify the XML signature in the XML file against the key. 
         Dim result As Boolean = VerifyDetachedSignature(XmlFileName, 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 SignDetachedResource(URIString As String, XmlSigFileName As String, Key As RSA)
      ' Create a SignedXml object. 
      Dim signedXml As New SignedXml()

      ' Assign the key to the SignedXml object.
      signedXml.SigningKey = Key

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

      ' Add the passed URI to the reference object.
      reference.Uri = URIString

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

      ' Save the signed XML document to a file specified 
      ' using the passed string. 
      Dim xmltw As New XmlTextWriter(XmlSigFileName, New UTF8Encoding(False))
      xmlDigitalSignature.WriteTo(xmltw)
      xmltw.Close()
   End Sub  


   ' Verify the signature of an XML file against an asymetric  
   ' algorithm and return the result. 
   Public Shared Function VerifyDetachedSignature(XmlSigFileName As String, Key As RSA) As [Boolean]
      ' Create a new XML document. 
      Dim xmlDocument As New XmlDocument()

      ' Load the passedXML file into the document.
      xmlDocument.Load(XmlSigFileName)

      ' Create a new SignedXml object. 
      Dim signedXml As New SignedXml()

      ' 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 against the passed asymetric key 
      ' and return the result. 
      Return signedXml.CheckSignature(Key)
   End Function  
End Class
// 
// This example signs a file specified by a URI  
// using a detached signature. It then verifies   
// the signed XML. 
// 

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



class XMLDSIGDetached
{
	
    [STAThread]
    static void Main(string[] args)
    {
        // The URI to sign. 
        string resourceToSign = "http://www.microsoft.com";
		
        // The name of the file to which to save the XML signature. 
        string XmlFileName = "xmldsig.xml";

        try
        {

            // Generate a signing key.
            RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

            Console.WriteLine("Signing: {0}", resourceToSign);

            // Sign the detached resourceand save the signature in an XML file.
            SignDetachedResource(resourceToSign, XmlFileName, Key);

            Console.WriteLine("XML Signature was succesfully computed and saved to {0}.", XmlFileName);

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");

            //Verify the XML signature in the XML file against the key. 
            bool result = VerifyDetachedSignature(XmlFileName, 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 SignDetachedResource(string URIString, string XmlSigFileName, RSA Key)
    {
        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml();

        // Assign the key to the SignedXml object.
        signedXml.SigningKey = Key;

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

        // Add the passed URI to the reference object.
        reference.Uri = URIString;
		
        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

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

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

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

    }

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

        // Load the passedXML file into the document.
        xmlDocument.Load(XmlSigFileName);
	
        // Create a new SignedXml object.
        SignedXml signedXml = new SignedXml();

        // Find the "Signature" node and create a new 
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature against the passed asymetric key 
        // and return the result. 
        return signedXml.CheckSignature(Key);
    }

}
// 
// This example signs a file specified by a URI  
// using a detached signature. It then verifies   
// the signed XML. 
//
#using <System.dll>
#using <System.Xml.dll>
#using <System.Security.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. 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 SignDetachedResource( String^ URIString, String^ XmlSigFileName, RSA^ Key )
{

   // Create a SignedXml object.
   SignedXml^ signedXml = gcnew SignedXml;

   // Assign the key to the SignedXml object.
   signedXml->SigningKey = Key;

   // Create a reference to be signed.
   Reference^ reference = gcnew Reference;

   // Add the passed URI to the reference object.
   reference->Uri = URIString;

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

   // Save the signed XML document to a file specified 
   // using the passed string.
   XmlTextWriter^ xmltw = gcnew XmlTextWriter( XmlSigFileName,gcnew UTF8Encoding( false ) );
   xmlDigitalSignature->WriteTo( xmltw );
   xmltw->Close();
}


// Verify the signature of an XML file against an asymetric  
// algorithm and return the result. 
static Boolean VerifyDetachedSignature( String^ XmlSigFileName, RSA^ Key )
{

   // Create a new XML document.
   XmlDocument^ xmlDocument = gcnew XmlDocument;

   // Load the passedXML file into the document.
   xmlDocument->Load( XmlSigFileName );

   // Create a new SignedXml object.
   SignedXml^ signedXml = gcnew SignedXml;

   // Find the "Signature" node and create a new 
   // XmlNodeList object.
   XmlNodeList^ nodeList = xmlDocument->GetElementsByTagName( "Signature" );

   // Load the signature node.
   signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList[ 0 ]) );

   // Check the signature against the passed asymetric key 
   // and return the result. 
   return signedXml->CheckSignature( Key );
}

int main()
{

   // The URI to sign.
   String^ resourceToSign = "http://www.microsoft.com";

   // The name of the file to which to save the XML signature.
   String^ XmlFileName = "xmldsig.xml";
   try
   {

      // Generate a signing key.
      RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider;
      Console::WriteLine( "Signing: {0}", resourceToSign );

      // Sign the detached resourceand save the signature in an XML file.
      SignDetachedResource( resourceToSign, XmlFileName, Key );
      Console::WriteLine( "XML Signature was succesfully computed and saved to {0}.", XmlFileName );

      // Verify the signature of the signed XML.
      Console::WriteLine( "Verifying signature..." );

      //Verify the XML signature in the XML file against the key. 
      bool result = VerifyDetachedSignature( XmlFileName, 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 );
   }

}

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. 
' 
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
// 
// 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. 
//
#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;
}
Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.