SignedXml Class

SignedXml Class

 

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

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

System.Object
  System.Security.Cryptography.Xml.SignedXml

[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public class SignedXml

NameDescription
System_CAPS_pubmethodSignedXml()

Initializes a new instance of the SignedXml class.

System_CAPS_pubmethodSignedXml(XmlDocument)

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

System_CAPS_pubmethodSignedXml(XmlElement)

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

NameDescription
System_CAPS_pubpropertyEncryptedXml

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

System_CAPS_pubpropertyKeyInfo

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

System_CAPS_pubpropertyResolver

Sets the current XmlResolver object.

System_CAPS_pubpropertySafeCanonicalizationMethods

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

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

System_CAPS_pubpropertySignature

Gets the Signature object of the current SignedXml object.

System_CAPS_pubpropertySignatureFormatValidator

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

System_CAPS_pubpropertySignatureLength

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

System_CAPS_pubpropertySignatureMethod

Gets the signature method of the current SignedXml object.

System_CAPS_pubpropertySignatureValue

Gets the signature value of the current SignedXml object.

System_CAPS_pubpropertySignedInfo

Gets the SignedInfo object of the current SignedXml object.

System_CAPS_pubpropertySigningKey

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

System_CAPS_pubpropertySigningKeyName

This API supports the product infrastructure and is not intended to be used directly from your code. Gets or sets the name of the installed key to be used for signing the SignedXml object.

NameDescription
System_CAPS_pubmethodAddObject(DataObject)

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

System_CAPS_pubmethodAddReference(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.

System_CAPS_pubmethodCheckSignature()

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

System_CAPS_pubmethodCheckSignature(AsymmetricAlgorithm)

Determines whether the Signature property verifies for the specified key.

System_CAPS_pubmethodCheckSignature(KeyedHashAlgorithm)

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

System_CAPS_pubmethodCheckSignature(X509Certificate2, Boolean)

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

System_CAPS_pubmethodCheckSignatureReturningKey(AsymmetricAlgorithm)

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

System_CAPS_pubmethodComputeSignature()

Computes an XML digital signature.

System_CAPS_pubmethodComputeSignature(KeyedHashAlgorithm)

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

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_pubmethodGetIdElement(XmlDocument, String)

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

System_CAPS_protmethodGetPublicKey()

Returns the public key of a signature.

System_CAPS_pubmethodGetType()

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

System_CAPS_pubmethodGetXml()

Returns the XML representation of a SignedXml object.

System_CAPS_pubmethodLoadXml(XmlElement)

Loads a SignedXml 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.)

NameDescription
System_CAPS_protfieldm_signature

This API supports the product infrastructure and is not intended to be used directly from your code. Represents the Signature object of the current SignedXml object.

System_CAPS_protfieldm_strSigningKeyName

This API supports the product infrastructure and is not intended to be used directly from your code. Represents the name of the installed key to be used for signing the SignedXml object.

System_CAPS_pubfieldSystem_CAPS_staticXmlDecryptionTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigBase64TransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigC14NTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigC14NWithCommentsTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigCanonicalizationUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigCanonicalizationWithCommentsUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigDSAUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigEnvelopedSignatureTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigExcC14NTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigExcC14NWithCommentsTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigHMACSHA1Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigMinimalCanonicalizationUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigNamespaceUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigRSASHA1Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigRSASHA256Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigRSASHA384Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigRSASHA512Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigSHA1Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigSHA256Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigSHA384Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigSHA512Url

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigXPathTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlDsigXsltTransformUrl

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

System_CAPS_pubfieldSystem_CAPS_staticXmlLicenseTransformUrl

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

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.

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.

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.

System_CAPS_noteNote

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

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.

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.

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.

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.

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.

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.

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

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

.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:
© 2016 Microsoft