Export (0) Print
Expand All

Signature Class

Represents the <Signature> element of an XML signature.

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

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

'Declaration
<HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort := True)> _
Public Class Signature

The Signature type exposes the following members.

  NameDescription
Public methodSignatureInitializes a new instance of the Signature class.
Top

  NameDescription
Public propertyIdGets or sets the ID of the current Signature.
Public propertyKeyInfoGets or sets the KeyInfo of the current Signature.
Public propertyObjectListGets or sets a list of objects to be signed.
Public propertySignatureValueGets or sets the value of the digital signature.
Public propertySignedInfoGets or sets the SignedInfo of the current Signature.
Top

  NameDescription
Public methodAddObjectAdds a DataObject to the list of objects to be signed.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetXmlReturns the XML representation of the Signature.
Public methodLoadXmlLoads a Signature state from an XML element.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

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

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.

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. 

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 

            ' Sign an XML file and save the signature to a  
            ' new file.
            SignXmlFile("Test.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")

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

        ' 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

        ' Get the signature object from the SignedXml object. 
        Dim XMLSignature As Signature = signedXml.Signature

        ' Create a reference to be signed.  Pass ""  
        ' to specify that all of the current XML 
        ' document should be signed. 
        Dim reference As New Reference("")

        ' Add an enveloped transformation to the reference. 
        Dim env As New 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). 
        Dim keyInfo As New KeyInfo()
        keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA)))

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

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. 

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 

            ' 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...")

            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 SignDetachedResource(ByVal URIString As String, ByVal XmlSigFileName As String, ByVal Key As RSA)
        ' Check the arguments.   
        If URIString Is Nothing Then 
            Throw New ArgumentNullException("URIString")
        End If 
        If XmlSigFileName Is Nothing Then 
            Throw New ArgumentNullException("XmlSigFileName")
        End If 
        If Key Is Nothing Then 
            Throw New ArgumentNullException("Key")
        End If 
        ' Create a SignedXml object. 
        Dim signedXml As New SignedXml()

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

        ' Get the signature object from the SignedXml object. 
        Dim XMLSignature As Signature = signedXml.Signature

        ' 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 object to the Signature object.
        XMLSignature.SignedInfo.AddReference(reference)

        ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). 
        Dim keyInfo As New KeyInfo()
        keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA)))

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

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

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