Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

EncryptedXml Class

Represents the process model for implementing XML encryption.

Namespace:  System.Security.Cryptography.Xml
Assembly:  System.Security (in System.Security.dll)
'Declaration
Public Class EncryptedXml
'Usage
Dim instance As EncryptedXml

The EncryptedXml class is the main class used for XML encryption in the .NET Framework. XML Encryption is a standards-based, interoperable way to encrypt all or part of an XML document or any arbitrary data. The .NET Framework XML encryption classes implement the World Wide Web Consortium (W3C) specification for XML encryption located at http://www.w3.org/TR/xmlenc-core/.

Use the EncryptedXml class whenever you need to share encrypted XML data between applications or organizations in a standard way. Any data encrypted using this class can be decrypted by any implementation of the W3C specification for XML encryption.

XML encryption replaces any plain text XML element or document with the <EncryptedData> element, which contains an encrypted (or cipher text) representation of plain text XML or any arbitrary data. The <EncryptedData> element can optionally contain information about where to find a key that will decrypt the cipher text, and which cryptographic algorithm was used to encrypt the plain text.

The <EncryptedKey> element is similar to the <EncryptedData> element in style and usage, except that it allows you to encrypt a key that will decrypt the value of the <EncryptedData> element. Note that the <EncryptedKey> element and the <EncryptedData> element will never contain an unencrypted key.

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 encrypted data.

  • Include the location of the key in the Uniform Resource Identifier (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.

  • Include an encrypted key in the <EncryptedKey> element. Both parties must agree on the key that decrypts the encrypted key before they exchange encrypted data. You can optionally include a name or location of the key that will decrypt the key in the <EncryptedKey> element.

The following code example demonstrates how to create a simple utility class that uses the TripleDES algorithm to encrypt an XML document.

Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml



Module Program

    Sub Main(ByVal args() As String)

        ' Create an XmlDocument object. 
        Dim xmlDoc As New XmlDocument()

        ' Load an XML file into the XmlDocument object.
        xmlDoc.PreserveWhitespace = True
        xmlDoc.Load("test.xml")


        ' Create a new TripleDES key.  
        Dim tDESkey As New TripleDESCryptoServiceProvider()

        ' Create a new instance of the TrippleDESDocumentEncryption object 
        ' defined in this sample. 
        Dim xmlTDES As New TrippleDESDocumentEncryption(xmlDoc, tDESkey)

        Try 
            ' Encrypt the "creditcard" element.
            xmlTDES.Encrypt("creditcard")

            ' Display the encrypted XML to the console.
            Console.WriteLine("Encrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlTDES.Doc.OuterXml)

            ' Decrypt the "creditcard" element.
            xmlTDES.Decrypt()

            ' Display the encrypted XML to the console.
            Console.WriteLine()
            Console.WriteLine("Decrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlTDES.Doc.OuterXml)
        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally 
            ' Clear the TripleDES key.
            xmlTDES.Clear()
        End Try 

    End Sub 'Main 
End Module 'Program



Class TrippleDESDocumentEncryption
    Protected docValue As XmlDocument
    Protected algValue As TripleDES


    Public Sub New(ByVal Doc As XmlDocument, ByVal Key As TripleDES)
        If Not (Doc Is Nothing) Then
            docValue = Doc
        Else 
            Throw New ArgumentNullException("Doc")
        End If 

        If Not (Key Is Nothing) Then

            algValue = Key
        Else 
            Throw New ArgumentNullException("Key")
        End If 

    End Sub 


    Public Property Doc() As XmlDocument
        Get 
            Return docValue
        End Get 
        Set(ByVal value As XmlDocument)
            docValue = value
        End Set 
    End Property 

    Public Property Alg() As TripleDES
        Get 
            Return algValue
        End Get 
        Set(ByVal value As TripleDES)
            algValue = value
        End Set 
    End Property 

    Public Sub Clear()
        If Not (algValue Is Nothing) Then
            algValue.Clear()
        Else 
            Throw New Exception("No TripleDES key was found to clear.")
        End If 

    End Sub 


    Public Sub Encrypt(ByVal Element As String)
        ' Find the element by name and create a new 
        ' XmlElement object. 
        Dim inputElement As XmlElement = docValue.GetElementsByTagName(Element)(0)

        ' If the element was not found, throw an exception. 
        If inputElement Is Nothing Then 
            Throw New Exception("The element was not found.")
        End If 

        ' Create a new EncryptedXml object. 
        Dim exml As New EncryptedXml(docValue)

        ' Encrypt the element using the symmetric key. 
        Dim rgbOutput As Byte() = exml.EncryptData(inputElement, algValue, False)

        ' Create an EncryptedData object and populate it. 
        Dim ed As New EncryptedData()

        ' Specify the namespace URI for XML encryption elements.
        ed.Type = EncryptedXml.XmlEncElementUrl

        ' Specify the namespace URI for the TrippleDES algorithm.
        ed.EncryptionMethod = New EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl)

        ' Create a CipherData element.
        ed.CipherData = New CipherData()

        ' Set the CipherData element to the value of the encrypted XML element.
        ed.CipherData.CipherValue = rgbOutput

        ' Replace the plaintext XML elemnt with an EncryptedData element.
        EncryptedXml.ReplaceElement(inputElement, ed, False)

    End Sub 


    Public Sub Decrypt()

        ' XmlElement object. 
        Dim encryptedElement As XmlElement = docValue.GetElementsByTagName("EncryptedData")(0)

        ' If the EncryptedData element was not found, throw an exception. 
        If encryptedElement Is Nothing Then 
            Throw New Exception("The EncryptedData element was not found.")
        End If 

        ' Create an EncryptedData object and populate it. 
        Dim ed As New EncryptedData()
        ed.LoadXml(encryptedElement)

        ' Create a new EncryptedXml object. 
        Dim exml As New EncryptedXml()

        ' Decrypt the element using the symmetric key. 
        Dim rgbOutput As Byte() = exml.DecryptData(ed, algValue)

        ' Replace the encryptedData element with the plaintext XML elemnt.
        exml.ReplaceData(encryptedElement, rgbOutput)

    End Sub 
End Class

The following code example demonstrates how to encrypt an XML document using a symmetric key. This example does not include any key information in the encrypted XML document.

Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml



Module Program

    Sub Main(ByVal args() As String)

        ' Create an XmlDocument object. 
        Dim xmlDoc As New XmlDocument()

        ' Load an XML file into the XmlDocument object. 
        Try
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
        Catch e As Exception
            Console.WriteLine(e.Message)
            Return 
        End Try 

        ' Create a new TripleDES key.  
        Dim tDESkey As New TripleDESCryptoServiceProvider()


        Try 
            ' Encrypt the "creditcard" element.
            Encrypt(xmlDoc, "creditcard", tDESkey)

            ' Display the encrypted XML to the console.
            Console.WriteLine("Encrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)

            ' Decrypt the "creditcard" element.
            Decrypt(xmlDoc, tDESkey)

            ' Display the encrypted XML to the console.
            Console.WriteLine()
            Console.WriteLine("Decrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)
        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally 
            ' Clear the TripleDES key.
            tDESkey.Clear()
        End Try 

    End Sub 


    Sub Encrypt(ByVal Doc As XmlDocument, ByVal ElementToEncrypt As String, ByVal Alg As SymmetricAlgorithm)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        If ElementToEncrypt Is Nothing Then 
            Throw New ArgumentNullException("ElementToEncrypt")
        End If 
        If Alg Is Nothing Then 
            Throw New ArgumentNullException("Alg")
        End If 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Find the specified element in the XmlDocument 
        ' object and create a new XmlElemnt object. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        Dim elementEncrypt As XmlElement = Doc.GetElementsByTagName(ElementToEncrypt)(0)


        ' Throw an XmlException if the element was not found. 
        If ElementToEncrypt Is Nothing Then 
            Throw New XmlException("The specified element was not found")
        End If 

        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Create a new instance of the EncryptedXml class  
        ' and use it to encrypt the XmlElement with the  
        ' symmetric key. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        Dim eXml As New EncryptedXml()

        Dim encryptedElement As Byte() = eXml.EncryptData(elementEncrypt, Alg, False)

        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Construct an EncryptedData object and populate 
        ' it with the desired encryption information. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 

        Dim edElement As New EncryptedData()
        edElement.Type = EncryptedXml.XmlEncElementUrl

        ' Create an EncryptionMethod element so that the  
        ' receiver knows which algorithm to use for decryption. 
        ' Determine what kind of algorithm is being used and 
        ' supply the appropriate URL to the EncryptionMethod element. 
        Dim encryptionMethod As String = Nothing 

        If TypeOf Alg Is TripleDES Then
            encryptionMethod = EncryptedXml.XmlEncTripleDESUrl
        ElseIf TypeOf Alg Is DES Then
            encryptionMethod = EncryptedXml.XmlEncDESUrl
        ElseIf TypeOf Alg Is Rijndael Then 
            Select Case Alg.KeySize
                Case 128
                    encryptionMethod = EncryptedXml.XmlEncAES128Url
                Case 192
                    encryptionMethod = EncryptedXml.XmlEncAES192Url
                Case 256
                    encryptionMethod = EncryptedXml.XmlEncAES256Url
            End Select 
        Else 
            ' Throw an exception if the transform is not in the previous categories 
            Throw New CryptographicException("The specified algorithm is not supported for XML Encryption.")
        End If

        edElement.EncryptionMethod = New EncryptionMethod(encryptionMethod)

        ' Add the encrypted element data to the  
        ' EncryptedData object.
        edElement.CipherData.CipherValue = encryptedElement

        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Replace the element from the original XmlDocument 
        ' object with the EncryptedData element. 
        '''''''''''''''''''''''''''''''''''''''''''''''''''
        EncryptedXml.ReplaceElement(elementEncrypt, edElement, False)

    End Sub 'Encrypt


    Sub Decrypt(ByVal Doc As XmlDocument, ByVal Alg As SymmetricAlgorithm)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        If Alg Is Nothing Then 
            Throw New ArgumentNullException("Alg")
        End If 
        ' Find the EncryptedData element in the XmlDocument. 
        Dim encryptedElement As XmlElement = Doc.GetElementsByTagName("EncryptedData")(0)

        ' If the EncryptedData element was not found, throw an exception. 
        If encryptedElement Is Nothing Then 
            Throw New XmlException("The EncryptedData element was not found.")
        End If 

        ' Create an EncryptedData object and populate it. 
        Dim edElement As New EncryptedData()
        edElement.LoadXml(encryptedElement)

        ' Create a new EncryptedXml object. 
        Dim exml As New EncryptedXml()

        ' Decrypt the element using the symmetric key. 
        Dim rgbOutput As Byte() = exml.DecryptData(edElement, Alg)

        ' Replace the encryptedData element with the plaintext XML element.
        exml.ReplaceData(encryptedElement, rgbOutput)

    End Sub 
End Module

The following code example demonstrates how to encrypt an XML document using a symmetric key. This example embeds a key name in the encrypted XML document that the decrypting method uses to find the appropriate decryption key.

Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml



Module Program

    Sub Main(ByVal args() As String)

        ' Create an XmlDocument object. 
        Dim xmlDoc As New XmlDocument()

        ' Load an XML file into the XmlDocument object. 
        Try
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
        Catch e As Exception
            Console.WriteLine(e.Message)
            Return 
        End Try 

        ' Create a new TripleDES key.  
        Dim tDESkey As New TripleDESCryptoServiceProvider()


        Try 
            ' Encrypt the "creditcard" element.
            Encrypt(xmlDoc, "creditcard", tDESkey, "tDESKey")

            ' Display the encrypted XML to the console.
            Console.WriteLine("Encrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)

            ' Decrypt the "creditcard" element.
            Decrypt(xmlDoc, tDESkey, "tDESKey")

            ' Display the encrypted XML to the console.
            Console.WriteLine()
            Console.WriteLine("Decrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)
        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally 
            ' Clear the TripleDES key.
            tDESkey.Clear()
        End Try 

    End Sub 'Main


    Sub Encrypt(ByVal Doc As XmlDocument, ByVal ElementToEncrypt As String, ByVal Alg As SymmetricAlgorithm, ByVal KeyName As String)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        If ElementToEncrypt Is Nothing Then 
            Throw New ArgumentNullException("ElementToEncrypt")
        End If 
        If Alg Is Nothing Then 
            Throw New ArgumentNullException("Alg")
        End If 
        ''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Find the specified element in the XmlDocument 
        ' object and create a new XmlElemnt object. 
        ''''''''''''''''''''''''''''''''''''''''''''''''' 
        Dim elementEncrypt As XmlElement = Doc.GetElementsByTagName(ElementToEncrypt)(0)


        ' Throw an XmlException if the element was not found. 
        If elementToEncrypt Is Nothing Then 
            Throw New XmlException("The specified element was not found")
        End If 

        ''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Create a new instance of the EncryptedXml class  
        ' and use it to encrypt the XmlElement with the  
        ' symmetric key. 
        ''''''''''''''''''''''''''''''''''''''''''''''''' 
        Dim eXml As New EncryptedXml()

        Dim encryptedElement As Byte() = eXml.EncryptData(elementEncrypt, Alg, False)

        ''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Construct an EncryptedData object and populate 
        ' it with the desired encryption information. 
        ''''''''''''''''''''''''''''''''''''''''''''''''' 

        Dim edElement As New EncryptedData()
        edElement.Type = EncryptedXml.XmlEncElementUrl

        ' Create an EncryptionMethod element so that the  
        ' receiver knows which algorithm to use for decryption. 
        ' Determine what kind of algorithm is being used and 
        ' supply the appropriate URL to the EncryptionMethod element. 
        Dim encryptionMethod As String = Nothing 

        If TypeOf Alg Is TripleDES Then
            encryptionMethod = EncryptedXml.XmlEncTripleDESUrl
        ElseIf TypeOf Alg Is DES Then
            encryptionMethod = EncryptedXml.XmlEncDESUrl
        ElseIf TypeOf Alg Is Rijndael Then 
            Select Case Alg.KeySize
                Case 128
                    encryptionMethod = EncryptedXml.XmlEncAES128Url
                Case 192
                    encryptionMethod = EncryptedXml.XmlEncAES192Url
                Case 256
                    encryptionMethod = EncryptedXml.XmlEncAES256Url
            End Select 
        Else 
            ' Throw an exception if the transform is not in the previous categories 
            Throw New CryptographicException("The specified algorithm is not supported for XML Encryption.")
        End If

        edElement.EncryptionMethod = New EncryptionMethod(encryptionMethod)

        ' Set the KeyInfo element to specify the 
        ' name of a key. 
        ' Create a new KeyInfo element.
        edElement.KeyInfo = New KeyInfo()

        ' Create a new KeyInfoName element. 
        Dim kin As New KeyInfoName()

        ' Specify a name for the key.
        kin.Value = KeyName

        ' Add the KeyInfoName element.
        edElement.KeyInfo.AddClause(kin)

        ' Add the encrypted element data to the  
        ' EncryptedData object.
        edElement.CipherData.CipherValue = encryptedElement

        ''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Replace the element from the original XmlDocument 
        ' object with the EncryptedData element. 
        '''''''''''''''''''''''''''''''''''''''''''''''''
        EncryptedXml.ReplaceElement(elementEncrypt, edElement, False)

    End Sub 


    Sub Decrypt(ByVal Doc As XmlDocument, ByVal Alg As SymmetricAlgorithm, ByVal KeyName As String)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        If Alg Is Nothing Then 
            Throw New ArgumentNullException("Alg")
        End If 
        If KeyName Is Nothing Then 
            Throw New ArgumentNullException("KeyName")
        End If 
        ' Create a new EncryptedXml object. 
        Dim exml As New EncryptedXml(Doc)

        ' Add a key-name mapping. 
        ' This method can only decrypt documents 
        ' that present the specified key name.
        exml.AddKeyNameMapping(KeyName, Alg)

        ' Decrypt the element.
        exml.DecryptDocument()

    End Sub 
End Module

The following code example demonstrates how to encrypt an XML document using an asymmetric key. This example creates a symmetric session key to encrypt the document and then uses the asymmetric key to embed an encrypted version of the session key into the XML document.

Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml



Module Program

    Sub Main(ByVal args() As String)

        ' Create an XmlDocument object. 
        Dim xmlDoc As New XmlDocument()

        ' Load an XML file into the XmlDocument object. 
        Try
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
        Catch e As Exception
            Console.WriteLine(e.Message)
            Return 
        End Try 

        ' Create a new RSA key.  This key will encrypt a symmetric key, 
        ' which will then be imbedded in the XML document.   
        Dim rsaKey = New RSACryptoServiceProvider()


        Try 
            ' Encrypt the "creditcard" element.
            Encrypt(xmlDoc, "creditcard", rsaKey, "rsaKey")

            ' Display the encrypted XML to the console.
            Console.WriteLine("Encrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)
            xmlDoc.Save("test.xml")

            ' Decrypt the "creditcard" element.
            Decrypt(xmlDoc, rsaKey, "rsaKey")

            ' Display the encrypted XML to the console.
            Console.WriteLine()
            Console.WriteLine("Decrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)
            xmlDoc.Save("test.xml")
        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally 
            ' Clear the RSA key.
            rsaKey.Clear()
        End Try 

    End Sub 


    Sub Encrypt(ByVal Doc As XmlDocument, ByVal ElementToEncrypt As String, ByVal Alg As RSA, ByVal KeyName As String)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        If ElementToEncrypt Is Nothing Then 
            Throw New ArgumentNullException("ElementToEncrypt")
        End If 
        If Alg Is Nothing Then 
            Throw New ArgumentNullException("Alg")
        End If 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Find the specified element in the XmlDocument 
        ' object and create a new XmlElemnt object. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        Dim elementEncrypt As XmlElement = Doc.GetElementsByTagName(ElementToEncrypt)(0)

        ' Throw an XmlException if the element was not found. 
        If elementToEncrypt Is Nothing Then 
            Throw New XmlException("The specified element was not found")
        End If 

        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Create a new instance of the EncryptedXml class  
        ' and use it to encrypt the XmlElement with the  
        ' a new random symmetric key. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Create a 256 bit Rijndael key. 
        Dim sessionKey As New RijndaelManaged()
        sessionKey.KeySize = 256

        Dim eXml As New EncryptedXml()

        Dim encryptedElement As Byte() = eXml.EncryptData(elementEncrypt, sessionKey, False)

        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Construct an EncryptedData object and populate 
        ' it with the desired encryption information. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 

        Dim edElement As New EncryptedData()
        edElement.Type = EncryptedXml.XmlEncElementUrl

        ' Create an EncryptionMethod element so that the  
        ' receiver knows which algorithm to use for decryption.
        edElement.EncryptionMethod = New EncryptionMethod(EncryptedXml.XmlEncAES256Url)

        ' Encrypt the session key and add it to an EncryptedKey element. 
        Dim ek As New EncryptedKey()

        Dim encryptedKey As Byte() = EncryptedXml.EncryptKey(sessionKey.Key, Alg, False)

        ek.CipherData = New CipherData(encryptedKey)

        ek.EncryptionMethod = New EncryptionMethod(EncryptedXml.XmlEncRSA15Url)

        ' Set the KeyInfo element to specify the 
        ' name of the RSA key. 
        ' Create a new KeyInfo element.
        edElement.KeyInfo = New KeyInfo()

        ' Create a new KeyInfoName element. 
        Dim kin As New KeyInfoName()

        ' Specify a name for the key.
        kin.Value = KeyName

        ' Add the KeyInfoName element to the  
        ' EncryptedKey object.
        ek.KeyInfo.AddClause(kin)

        ' Add the encrypted key to the  
        ' EncryptedData object.
        edElement.KeyInfo.AddClause(New KeyInfoEncryptedKey(ek))

        ' Add the encrypted element data to the  
        ' EncryptedData object.
        edElement.CipherData.CipherValue = encryptedElement

        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Replace the element from the original XmlDocument 
        ' object with the EncryptedData element. 
        '''''''''''''''''''''''''''''''''''''''''''''''''''
        EncryptedXml.ReplaceElement(elementEncrypt, edElement, False)

    End Sub 


    Sub Decrypt(ByVal Doc As XmlDocument, ByVal Alg As RSA, ByVal KeyName As String)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        If Alg Is Nothing Then 
            Throw New ArgumentNullException("Alg")
        End If 
        If KeyName Is Nothing Then 
            Throw New ArgumentNullException("KeyName")
        End If 
        ' Create a new EncryptedXml object. 
        Dim exml As New EncryptedXml(Doc)

        ' Add a key-name mapping. 
        ' This method can only decrypt documents 
        ' that present the specified key name.
        exml.AddKeyNameMapping(KeyName, Alg)

        ' Decrypt the element.
        exml.DecryptDocument()

    End Sub 
End Module

The following code example demonstrates how to encrypt an XML document using an X.509 certificate. This example creates a symmetric session key to encrypt the document and then uses the X.509 certificate to embed an encrypted version of the session key into the XML document.

Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Security.Cryptography.X509Certificates



Module Program

    Sub Main(ByVal args() As String)

        ' Create an XmlDocument object. 
        Dim xmlDoc As New XmlDocument()

        ' Load an XML file into the XmlDocument object. 
        Try
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
        Catch e As Exception
            Console.WriteLine(e.Message)
            Return 
        End Try 

        ' Create a new X509Certificate2 object by loading 
        ' an X.509 certificate file.  To use XML encryption  
        ' with an X.509 certificate, use an X509Certificate2  
        ' object to encrypt, but use a certificate in a certificate 
        ' store to decrypt. 
        ' You can create a new test certificate file using the  
        ' makecert.exe tool. 
        ' Create an X509Certificate2 object for encryption. 
        Dim cert As New X509Certificate2("test.pfx")

        ' Put the certificate in certificate store for decryption.   
        Dim store As New X509Store(StoreLocation.CurrentUser)

        store.Open(OpenFlags.ReadWrite)

        store.Add(cert)

        store.Close()


        Try 
            ' Encrypt the "creditcard" element.
            Encrypt(xmlDoc, "creditcard", cert)

            ' Display the encrypted XML to the console.
            Console.WriteLine("Encrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)

            ' Decrypt the "creditcard" element.
            Decrypt(xmlDoc)

            ' Display the encrypted XML to the console.
            Console.WriteLine()
            Console.WriteLine("Decrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try 

    End Sub 


    Sub Encrypt(ByVal Doc As XmlDocument, ByVal ElementToEncrypt As String, ByVal Cert As X509Certificate2)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        If ElementToEncrypt Is Nothing Then 
            Throw New ArgumentNullException("ElementToEncrypt")
        End If 
        If Cert Is Nothing Then 
            Throw New ArgumentNullException("Cert")
        End If 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Find the specified element in the XmlDocument 
        ' object and create a new XmlElemnt object. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        Dim elementEncrypt As XmlElement = Doc.GetElementsByTagName(ElementToEncrypt)(0) 


        ' Throw an XmlException if the element was not found. 
        If elementToEncrypt Is Nothing Then 
            Throw New XmlException("The specified element was not found")
        End If 

        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Create a new instance of the EncryptedXml class  
        ' and use it to encrypt the XmlElement with the  
        ' X.509 Certificate. 
        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        Dim eXml As New EncryptedXml()

        ' Encrypt the element. 
        Dim edElement As EncryptedData = eXml.Encrypt(elementEncrypt, Cert)


        ''''''''''''''''''''''''''''''''''''''''''''''''''' 
        ' Replace the element from the original XmlDocument 
        ' object with the EncryptedData element. 
        '''''''''''''''''''''''''''''''''''''''''''''''''''
        EncryptedXml.ReplaceElement(elementEncrypt, edElement, False)

    End Sub 


    Sub Decrypt(ByVal Doc As XmlDocument)
        ' Check the arguments.   
        If Doc Is Nothing Then 
            Throw New ArgumentNullException("Doc")
        End If 
        ' Create a new EncryptedXml object. 
        Dim exml As New EncryptedXml(Doc)

        ' Decrypt the XML document.
        exml.DecryptDocument()

    End Sub 
End Module
System.Object
  System.Security.Cryptography.Xml.EncryptedXml
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.