Partager via


Comment : signer des documents XML avec des signatures numériques

Mise à jour : novembre 2007

Vous pouvez utiliser les classes dans l'espace de noms System.Security.Cryptography.Xml pour signer un document XML ou une partie d'un document XML avec une signature numérique. Les signatures numériques XML (XMLDSIG) vous permettent de vérifier que les données n'ont pas été altérées après leur signature. Pour plus d'informations sur la norme XMLDSIG, consultez la spécification World Wide Web Consortium (W3C) à l'adresse http://www.w3.org/TR/xmldsig-core/.

L'exemple de code dans cette procédure montre comment signer numériquement un document XML entier et joindre la signature au document dans un élément <Signature>. L'exemple crée une clé de signature RSA, ajoute la clé à un conteneur de clé sécurisé, puis utilise la clé pour signer numériquement un document XML. La clé peut ensuite être récupérée pour vérifier la signature numérique XML ou être utilisée pour signer un autre document XML.

Pour plus d'informations sur la vérification d'une signature numérique XML qui a été créée à l'aide de cette procédure, consultez Comment : vérifier les signatures numériques de documents XML.

Signer un document XML numériquement

  1. Créez un objet CspParameters et spécifiez le nom du conteneur de clé.

    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
    
  2. Générez une clé symétrique à l'aide de la classe RSACryptoServiceProvider. La clé est enregistrée automatiquement dans le conteneur de clé lorsque vous passez l'objet CspParameters au constructeur de la classe RSACryptoServiceProvider. Cette clé sera utilisée pour signer le document XML.

    Dim rsaKey As New RSACryptoServiceProvider(cspParams)
    
    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
    
  3. Créez un objet XmlDocument en chargeant un fichier XML à partir du disque. L'objet XmlDocument contient l'élément XML à chiffrer.

    Dim xmlDoc As New XmlDocument()
    
    ' Load an XML file into the XmlDocument object.
    xmlDoc.PreserveWhitespace = True
    xmlDoc.Load("test.xml")
    
    XmlDocument xmlDoc = new XmlDocument();
    
    // Load an XML file into the XmlDocument object.
    xmlDoc.PreserveWhitespace = true;
    xmlDoc.Load("test.xml");
    
  4. Créez un objet SignedXml et passez-lui l'objet XmlDocument.

    Dim signedXml As New SignedXml(Doc)
    
    SignedXml signedXml = new SignedXml(Doc);
    
  5. Ajoutez la clé de signature RSA à l'objet SignedXml.

    signedXml.SigningKey = Key
    
    signedXml.SigningKey = Key;
    
  6. Créez un objet Reference qui décrit les éléments à signer. Pour signer le document entier, affectez à la propriété Uri la valeur "".

    ' Create a reference to be signed.
    Dim reference As New Reference()
    reference.Uri = ""
    
    // Create a reference to be signed.
    Reference reference = new Reference();
    reference.Uri = "";
    
  7. Ajoutez un objet XmlDsigEnvelopedSignatureTransform à l'objet Reference. Une transformation permet au vérificateur de représenter les données XML de la même manière que celle utilisée par le signataire. Les données XML pouvant être représentées de différentes façons, cette étape est vitale pour la vérification.

    Dim env As New XmlDsigEnvelopedSignatureTransform()
    reference.AddTransform(env)
    
    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);
    
  8. Ajoutez l'objet Reference à l'objet SignedXml.

    signedXml.AddReference(reference)
    
    signedXml.AddReference(reference);
    
  9. Calculez la signature en appelant la méthode ComputeSignature.

    signedXml.ComputeSignature()
    
    signedXml.ComputeSignature();
    
  10. Récupérez la représentation XML de la signature (un élément <Signature>) et enregistrez-la dans un nouvel objet XmlElement.

    Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
    
    XmlElement xmlDigitalSignature = signedXml.GetXml();
    
  11. Ajoutez l'élément à l'objet XmlDocument.

    Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, True))
    
    Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
    
  12. Enregistrez le document.

    xmlDoc.Save("test.xml")
    
    xmlDoc.Save("test.xml");
    

Exemple

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



Module SignXML


    Sub Main(ByVal args() As String)
        Try
            ' Create a new CspParameters object to specify
            ' a key container.
            Dim cspParams As New CspParameters()
            cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
            ' Create a new RSA signing key and save it in the container. 
            Dim rsaKey As New RSACryptoServiceProvider(cspParams)
            ' Create a new XML document.
            Dim xmlDoc As New XmlDocument()

            ' Load an XML file into the XmlDocument object.
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
            ' Sign the XML document. 
            SignXml(xmlDoc, rsaKey)

            Console.WriteLine("XML file signed.")

            ' Save the document.
            xmlDoc.Save("test.xml")


        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try

    End Sub



    ' Sign an XML file. 
    ' This document cannot be verified unless the verifying 
    ' code has the key with which it was signed.
    Sub SignXml(ByVal Doc As XmlDocument, ByVal Key As RSA)
        ' Check arguments.
        If Doc Is Nothing Then
            Throw New ArgumentException("Doc")
        End If
        If Key Is Nothing Then
            Throw New ArgumentException("Key")
        End If
        ' Create a SignedXml object.
        Dim signedXml As New SignedXml(Doc)
        ' Add the key to the SignedXml document.
        signedXml.SigningKey = Key
        ' Create a reference to be signed.
        Dim reference As New Reference()
        reference.Uri = ""
        ' Add an enveloped transformation to the reference.
        Dim env As 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.
        Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
        ' Append the element to the XML document.
        Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, True))
    End Sub
End Module
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;

public class SignXML
{

    public static void Main(String[] args)
    {
        try
        {
            // Create a new CspParameters object to specify
            // a key container.
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";

            // Create a new RSA signing key and save it in the container. 
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

            // Create a new XML document.
            XmlDocument xmlDoc = new XmlDocument();

            // Load an XML file into the XmlDocument object.
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load("test.xml");

            // Sign the XML document. 
            SignXml(xmlDoc, rsaKey);

            Console.WriteLine("XML file signed.");

            // Save the document.
            xmlDoc.Save("test.xml");



        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }


    // Sign an XML file. 
    // This document cannot be verified unless the verifying 
    // code has the key with which it was signed.
    public static void SignXml(XmlDocument Doc, RSA Key)
    {
        // Check arguments.
        if (Doc == null)
            throw new ArgumentException("Doc");
        if (Key == null)
            throw new ArgumentException("Key");

        // 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));

    }
}

Cet exemple suppose qu'un fichier nommé "test.xml" existe dans le même répertoire que le programme compilé. 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 ou transférer la clé privée d'une paire de clés asymétrique en texte brut. Pour plus d'informations sur les clés de chiffrement symétriques et asymétriques, consultez Génération de clés pour le chiffrement et le déchiffrement.

N'incorporez jamais directement une clé privée dans votre code source. Les clés incorporées peuvent être lues facilement à partir d'un assembly à l'aide du MSIL Disassembler (Ildasm.exe) ou en ouvrant l'assembly dans un éditeur de texte tel que le Bloc-notes.

Voir aussi

Tâches

Comment : vérifier les signatures numériques de documents XML

Référence

System.Security.Cryptography.Xml

Autres ressources

Chiffrement XML et signatures numériques