SignedXml Class

Definition

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

C#
public class SignedXml
Inheritance
SignedXml

Examples

The following code example shows how to sign and verify an entire XML document using an enveloped signature.

C#
//
// 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.
           RSA Key = RSA.Create();

           // 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 asymmetric 
    // 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.

C#
//
// 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.
       RSA Key = RSA.Create();

       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
           // RSA instance.
           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();
    }
}

Remarks

For more information about this API, see Supplemental API remarks for SignedXml.

Constructors

SignedXml()

Initializes a new instance of the SignedXml class.

SignedXml(XmlDocument)

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

SignedXml(XmlElement)

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

Fields

m_signature

Represents the Signature object of the current SignedXml object.

m_strSigningKeyName

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

XmlDecryptionTransformUrl

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

XmlDsigBase64TransformUrl

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

XmlDsigC14NTransformUrl

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

XmlDsigC14NWithCommentsTransformUrl

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

XmlDsigCanonicalizationUrl

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

XmlDsigCanonicalizationWithCommentsUrl

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

XmlDsigDSAUrl

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

XmlDsigEnvelopedSignatureTransformUrl

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

XmlDsigExcC14NTransformUrl

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

XmlDsigExcC14NWithCommentsTransformUrl

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

XmlDsigHMACSHA1Url

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

XmlDsigMinimalCanonicalizationUrl

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

XmlDsigNamespaceUrl

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

XmlDsigRSASHA1Url

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

XmlDsigRSASHA256Url

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

XmlDsigRSASHA384Url

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

XmlDsigRSASHA512Url

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

XmlDsigSHA1Url

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

XmlDsigSHA256Url

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

XmlDsigSHA384Url

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

XmlDsigSHA512Url

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

XmlDsigXPathTransformUrl

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

XmlDsigXsltTransformUrl

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

XmlLicenseTransformUrl

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

Properties

EncryptedXml

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

KeyInfo

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

Resolver

Sets the current XmlResolver object.

SafeCanonicalizationMethods

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

Signature

Gets the Signature object of the current SignedXml object.

SignatureFormatValidator

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

SignatureLength

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

SignatureMethod

Gets the signature method of the current SignedXml object.

SignatureValue

Gets the signature value of the current SignedXml object.

SignedInfo

Gets the SignedInfo object of the current SignedXml object.

SigningKey

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

SigningKeyName

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

Methods

AddObject(DataObject)

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

AddReference(Reference)

Adds a Reference object to the SignedXml object that describes a digest method, digest value, and transform to use for creating an XML digital signature.

CheckSignature()

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

CheckSignature(AsymmetricAlgorithm)

Determines whether the Signature property verifies for the specified key.

CheckSignature(KeyedHashAlgorithm)

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

CheckSignature(X509Certificate2, Boolean)

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

CheckSignatureReturningKey(AsymmetricAlgorithm)

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

ComputeSignature()

Computes an XML digital signature.

ComputeSignature(KeyedHashAlgorithm)

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

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetIdElement(XmlDocument, String)

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

GetPublicKey()

Returns the public key of a signature.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetXml()

Returns the XML representation of a SignedXml object.

LoadXml(XmlElement)

Loads a SignedXml state from an XML element.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

Product Versions
.NET 8 (package-provided), 9 (package-provided)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7 (package-provided), 4.7, 4.7.1 (package-provided), 4.7.1, 4.7.2 (package-provided), 4.7.2, 4.8 (package-provided), 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

See also