Partager via


Comment : chiffrer des éléments XML avec des clés symétriques

Mise à jour : novembre 2007

Vous pouvez utiliser les classes dans l'espace de noms System.Security.Cryptography.Xml pour chiffrer un élément dans un document XML. Le chiffrement XML vous permet de stocker ou de transporter du XML sensible, sans risque que les données soient lues facilement. Cette procédure déchiffre un élément XML à l'aide de l'algorithme Advanced Encryption Standard (AES), également connu sous le nom de Rijndael.

Pour plus d'informations sur le déchiffrement d'un élément XML chiffré à l'aide de cette procédure, consultez Comment : déchiffrer des éléments XML avec des clés symétriques.

Lorsque vous utilisez un algorithme symétrique comme AES pour chiffrer des données XML, vous devez utiliser la même clé pour chiffrer et déchiffrer les données XML. L'exemple dans cette procédure suppose que le XML chiffré sera déchiffré à l'aide de la même clé, et que les parties de chiffrement et de déchiffrement sont en accord sur l'algorithme et la clé à utiliser. Cet exemple ne stocke pas et ne déchiffre pas la clé AES dans le XML chiffré.

Cet exemple est approprié pour les situations où une application seule doit chiffrer des données basées sur une clé de session stockée en mémoire ou basées sur une clé forte du point de vue du chiffrement dérivée d'un mot de passe. Pour les situations où deux applications ou plus doivent partager des données XML chiffrées, pensez à utiliser une méthode de chiffrement basée sur un algorithme asymétrique ou un certificat X.509.

Pour chiffrer un élément XML avec une clé symétrique

  1. Générez une clé symétrique à l'aide de la classe RijndaelManaged. Cette clé sera utilisée pour chiffrer l'élément XML.

    Dim key As RijndaelManaged = Nothing
    
    Try
        ' Create a new Rijndael key.
        key = New RijndaelManaged()
    
             RijndaelManaged key = null;
    
                try
                {
                    // Create a new Rijndael key.
                    key = new RijndaelManaged();
    
  2. Créez un objet XmlDocument en chargeant un fichier XML à partir du disque. L'objet XmlDocument contient l'élément XML à chiffrer.

    ' Load an XML document.
    Dim xmlDoc As New XmlDocument()
    xmlDoc.PreserveWhitespace = True
    xmlDoc.Load("test.xml")
    
                 // Load an XML document.
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load("test.xml");
    
  3. Recherchez l'élément spécifié dans l'objet XmlDocument et créez un objet XmlElement pour représenter l'élément que vous souhaitez chiffrer. Dans cet exemple, l'élément "creditcard" est chiffré.

    Dim elementToEncrypt As XmlElement = Doc.GetElementsByTagName(ElementName)(0)
    
             XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
    
  4. Créez une instance de la classe EncryptedXml et utilisez-la pour chiffrer le XmlElement avec la clé symétrique. La méthode EncryptData retourne l'élément chiffré sous la forme d'un tableau d'octets chiffrés.

    Dim eXml As New EncryptedXml()
    
    Dim encryptedElement As Byte() = eXml.EncryptData(elementToEncrypt, Key, False)
    
             EncryptedXml eXml = new EncryptedXml();
    
                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
    
  5. Créez un objet EncryptedData et remplissez-le avec l'identificateur d'URL de l'élément de chiffrement XML. Cet identificateur d'URL fait savoir à une partie de chiffrement que le XML contient un élément chiffré. Vous pouvez utiliser le champ XmlEncElementUrl pour spécifier l'identificateur d'URL.

    Dim edElement As New EncryptedData()
    edElement.Type = EncryptedXml.XmlEncElementUrl
    
             EncryptedData edElement = new EncryptedData();
                edElement.Type = EncryptedXml.XmlEncElementUrl;
    
  6. Créez un objet EncryptionMethod qui est initialisé à l'identificateur d'URL de l'algorithme de chiffrement utilisé pour générer la clé. Passez l'objet EncryptionMethod à la propriété EncryptionMethod.

    Dim encryptionMethod As String = Nothing
    
    If TypeOf Key Is TripleDES Then
        encryptionMethod = EncryptedXml.XmlEncTripleDESUrl
    ElseIf TypeOf Key Is DES Then
        encryptionMethod = EncryptedXml.XmlEncDESUrl
    End If
    If TypeOf Key Is Rijndael Then
        Select Case Key.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)
    
             string encryptionMethod = null;
    
                if (Key is TripleDES)
                {
                    encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
                }
                else if (Key is DES)
                {
                    encryptionMethod = EncryptedXml.XmlEncDESUrl;
                }
                if (Key is Rijndael)
                {
                    switch (Key.KeySize)
                    {
                        case 128:
                            encryptionMethod = EncryptedXml.XmlEncAES128Url;
                            break;
                        case 192:
                            encryptionMethod = EncryptedXml.XmlEncAES192Url;
                            break;
                        case 256:
                            encryptionMethod = EncryptedXml.XmlEncAES256Url;
                            break;
                    }
                }
                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.");
                }
    
                edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
    
  7. Ajoutez les données d'élément chiffrées à l'objet EncryptedData.

    edElement.CipherData.CipherValue = encryptedElement
    
             edElement.CipherData.CipherValue = encryptedElement;
    
  8. Remplacez l'élément de l'objet XmlDocument d'origine par l'élément EncryptedData.

    EncryptedXml.ReplaceElement(elementToEncrypt, edElement, False)
    
             EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
    

Exemple

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




Module Program

    Sub Main(ByVal args() As String)
        Dim key As RijndaelManaged = Nothing

        Try
            ' Create a new Rijndael key.
            key = New RijndaelManaged()
            ' Load an XML document.
            Dim xmlDoc As New XmlDocument()
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
            ' Encrypt the "creditcard" element.
            Encrypt(xmlDoc, "creditcard", key)

            Console.WriteLine("The element was encrypted")

            Console.WriteLine(xmlDoc.InnerXml)

            Decrypt(xmlDoc, key)

            Console.WriteLine("The element was decrypted")

            Console.WriteLine(xmlDoc.InnerXml)


        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally
            ' Clear the key.
            If Not (key Is Nothing) Then
                key.Clear()
            End If
        End Try

    End Sub


    Sub Encrypt(ByVal Doc As XmlDocument, ByVal ElementName As String, ByVal Key As SymmetricAlgorithm)
        ' Check the arguments.  
        If Doc Is Nothing Then
            Throw New ArgumentNullException("Doc")
        End If
        If ElementName Is Nothing Then
            Throw New ArgumentNullException("ElementToEncrypt")
        End If
        If Key Is Nothing Then
            Throw New ArgumentNullException("Alg")
        End If
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Find the specified element in the XmlDocument
        ' object and create a new XmlElemnt object.
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim elementToEncrypt As XmlElement = Doc.GetElementsByTagName(ElementName)(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(elementToEncrypt, Key, 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 Key Is TripleDES Then
            encryptionMethod = EncryptedXml.XmlEncTripleDESUrl
        ElseIf TypeOf Key Is DES Then
            encryptionMethod = EncryptedXml.XmlEncDESUrl
        End If
        If TypeOf Key Is Rijndael Then
            Select Case Key.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(elementToEncrypt, 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

using System;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;


namespace CSCrypto
{
    class Program
    {
        static void Main(string[] args)
        {
            RijndaelManaged key = null;

            try
            {
                // Create a new Rijndael key.
                key = new RijndaelManaged();
                // Load an XML document.
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load("test.xml");

                // Encrypt the "creditcard" element.
                Encrypt(xmlDoc, "creditcard", key);

                Console.WriteLine("The element was encrypted");

                Console.WriteLine(xmlDoc.InnerXml);

                Decrypt(xmlDoc, key);

                Console.WriteLine("The element was decrypted");

                Console.WriteLine(xmlDoc.InnerXml);

                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // Clear the key.
                if (key != null)
                {
                    key.Clear();
                }
            }

        }

        public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key)
        {
            // Check the arguments.  
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (ElementName == null)
                throw new ArgumentNullException("ElementToEncrypt");
            if (Key == null)
                throw new ArgumentNullException("Alg");

            ////////////////////////////////////////////////
            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            ////////////////////////////////////////////////
            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");

            }

            //////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class 
            // and use it to encrypt the XmlElement with the 
            // symmetric key.
            //////////////////////////////////////////////////

            EncryptedXml eXml = new EncryptedXml();

            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
            ////////////////////////////////////////////////
            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            ////////////////////////////////////////////////

            EncryptedData edElement = 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.

            string encryptionMethod = null;

            if (Key is TripleDES)
            {
                encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
            }
            else if (Key is DES)
            {
                encryptionMethod = EncryptedXml.XmlEncDESUrl;
            }
            if (Key is Rijndael)
            {
                switch (Key.KeySize)
                {
                    case 128:
                        encryptionMethod = EncryptedXml.XmlEncAES128Url;
                        break;
                    case 192:
                        encryptionMethod = EncryptedXml.XmlEncAES192Url;
                        break;
                    case 256:
                        encryptionMethod = EncryptedXml.XmlEncAES256Url;
                        break;
                }
            }
            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.");
            }

            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(elementToEncrypt, edElement, false);
        }

        public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg)
        {
            // Check the arguments.  
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (Alg == null)
                throw new ArgumentNullException("Alg");

            // Find the EncryptedData element in the XmlDocument.
            XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement;

            // If the EncryptedData element was not found, throw an exception.
            if (encryptedElement == null)
            {
                throw new XmlException("The EncryptedData element was not found.");
            }

            
            // Create an EncryptedData object and populate it.
            EncryptedData edElement = new EncryptedData();
            edElement.LoadXml(encryptedElement);

            // Create a new EncryptedXml object.
            EncryptedXml exml = new EncryptedXml();
            

            // Decrypt the element using the symmetric key.
            byte[] rgbOutput = exml.DecryptData(edElement, Alg);

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

        }

    }


}

Cet exemple suppose qu'un fichier nommé "test.xml" existe dans le même répertoire que le programme compilé. Il suppose également que "test.xml" contient un élément "creditcard". Vous pouvez placer le XML suivant dans un fichier appelé test.xml et l'utiliser avec cet exemple.

<root>
    <creditcard>
        <number>19834209</number>
        <expiry>02/02/2002</expiry>
    </creditcard>
</root>

Compilation du code

Sécurité

Vous ne devez jamais stocker une clé de chiffrement en texte brut ou transférer une clé entre des ordinateurs en texte brut. À la place, utilisez un conteneur de clé sécurisé pour stocker les clés de chiffrement.

Lorsque vous avez fini d'utiliser une clé de chiffrement, effacez-la de la mémoire en affectant la valeur zéro à chaque octet ou en appelant la méthode Clear de la classe de chiffrement managée.

Voir aussi

Tâches

Comment : déchiffrer des éléments XML avec des clés symétriques

Référence

System.Security.Cryptography.Xml

Autres ressources

Chiffrement XML et signatures numériques