Signature Class

 

Represents the <Signature> element of an XML signature.

Namespace:   System.Security.Cryptography.Xml
Assembly:  System.Security (in System.Security.dll)

System::Object
  System.Security.Cryptography.Xml::Signature

[HostProtectionAttribute(SecurityAction::LinkDemand, MayLeakOnAbort = true)]
public ref class Signature 

NameDescription
System_CAPS_pubmethodSignature()

Initializes a new instance of the Signature class.

NameDescription
System_CAPS_pubpropertyId

Gets or sets the ID of the current Signature.

System_CAPS_pubpropertyKeyInfo

Gets or sets the KeyInfo of the current Signature.

System_CAPS_pubpropertyObjectList

Gets or sets a list of objects to be signed.

System_CAPS_pubpropertySignatureValue

Gets or sets the value of the digital signature.

System_CAPS_pubpropertySignedInfo

Gets or sets the SignedInfo of the current Signature.

NameDescription
System_CAPS_pubmethodAddObject(DataObject^)

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

System_CAPS_pubmethodEquals(Object^)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodGetXml()

Returns the XML representation of the Signature.

System_CAPS_pubmethodLoadXml(XmlElement^)

Loads a Signature state from an XML element.

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

The Signature class represents the <Signature> element of an XML signature defined by the XML digital signature specification. The <Signature> element is the root element of an XML digital signature. The SignedInfo, SignatureValue, KeyInfo, and ObjectList properties encapsulate the subelements of the <Signature> element.

For more information about the <Signature> element, see the W3C specification at www.w3.org/TR/xmldsig-core/.

The following code example uses the Signature class with the SignedXml class to sign and verify an XML document using an envelope 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 )
{

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


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

   // Get the signature object from the SignedXml object.
   Signature^ XMLSignature = signedXml->Signature;

   // Create a reference to be signed.  Pass "" 
   // to specify that all of the current XML
   // document should be signed.
   Reference^ reference = gcnew Reference( L"" );

   // Add an enveloped transformation to the reference.
   XmlDsigEnvelopedSignatureTransform^ env = gcnew XmlDsigEnvelopedSignatureTransform;
   reference->AddTransform( env );

   // Add the Reference object to the Signature object.
   XMLSignature->SignedInfo->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) ) );

   // Add the KeyInfo object to the Reference object.
   XMLSignature->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
   {

      // Sign an XML file and save the signature to a 
      // new file.
      SignXmlFile( L"Test.xml", L"SignedExample.xml", Key );
      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;
}

The following code example uses the Signature class with the SignedXml class to sign an object and verify an XML document using a detached signature.

//
// This example signs a URL using an
// envelope 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;


namespace Sample
{
    public ref class SignVerifyEnvelope
    {
    public:
        static void Work()
        {
            // Generate a signing key.
            RSACryptoServiceProvider^ key = 
                gcnew RSACryptoServiceProvider();

            try
            {

                // Sign the detached resource and save the 
                // signature in an XML file.
                SignDetachedResource("http://www.microsoft.com",
                    "SignedExample.xml", key);

                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.");
                }
                Console::ReadLine();
            }

            catch (CryptographicException^ ex)
            {
                Console::WriteLine(ex->Message);
            }
            finally
            {
                // Clear resources associated with the 
                // RSACryptoServiceProvider.
                key->Clear();
            }
        }


        // Sign an XML file and save the signature in a new file.
        static void SignDetachedResource(String^ uri, 
            String^ xmlFileName, RSA^ key)
        {
            // Check the arguments.  
            if (uri->Length == 0)
            {
                throw gcnew ArgumentException("uri");
            }
            if (xmlFileName->Length == 0)
            {
                throw gcnew ArgumentException("xmlFileName");
            } 
            if (key->KeySize == 0)
            {
                throw gcnew ArgumentException("key");
            }
            // Create a SignedXml object.
            SignedXml^ signedXml = gcnew SignedXml();

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

            // Get the signature object from the SignedXml object.
            Signature^ xmlSignature = signedXml->Signature;

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

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

            // Add the Reference object to the Signature object.
            xmlSignature->SignedInfo->AddReference(reference);

            // Add an RSAKeyValue KeyInfo (optional; helps recipient
            // find key to validate).
            KeyInfo^ keyInfo = gcnew KeyInfo();
            keyInfo->AddClause(
                gcnew RSAKeyValue(key));

            // Add the KeyInfo object to the Reference object.
            xmlSignature->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();

            // Save the signed XML document to a file specified
            // using the passed string.
            XmlTextWriter^ xmlTextWriter = gcnew XmlTextWriter(
                xmlFileName, gcnew UTF8Encoding(false));

            xmlDigitalSignature->WriteTo(xmlTextWriter);
            xmlTextWriter->Close();
        }


        // Verify the signature of an XML file and return the result.
        static Boolean VerifyXmlFile(String^ documentName)
        {
            // Check the arguments.  
            if (documentName->Length == 0)
            {
                throw gcnew ArgumentException("documentName");
            }
            // 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(documentName);

            // 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(
                (XmlElement^) nodeList->Item(0));

            // Check the signature and return the result.
            return signedXml->CheckSignature();
        }
    };
}


int main()
{
    Sample::SignVerifyEnvelope::Work();
}

.NET Framework
Available since 1.1

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

Return to top
Show: