Share via


Gewusst wie: Überprüfen der digitalen Signaturen von XML-Dokumenten

Um die mit einer digitalen Signatur versehenen XML-Daten zu überprüfen, können Sie die Klassen im System.Security.Cryptography.Xml-Namespace verwenden. Durch digitale XML-Signaturen (XMLDSIG) können Daten nach dem Signieren nicht mehr geändert werden. Weitere Informationen über den XMLDSIG-Standard finden Sie in der W3C-Spezifikation (World Wide Web Consortium) unter http://www.w3.org/TR/xmldsig-core/ (nur auf Englisch verfügbar).

Das Codebeispiel in dieser Prozedur veranschaulicht das Überprüfen einer digitalen XML-Signatur, die in einem <Signature>-Element enthalten ist. Im Beispiel wird ein öffentlicher RSA-Schlüssel aus einem Schlüsselcontainer abgerufen und anschließend zum Überprüfen der Signatur verwendet.

Informationen zum Erstellen einer mit dieser Methode überprüfbaren digitalen Signatur finden Sie unter Gewusst wie: Signieren von XML-Dokumenten mit digitalen Signaturen.

So überprüfen Sie die digitale Signatur eines XML-Dokuments

  1. Zum Überprüfen des Dokuments müssen Sie den gleichen asymmetrischen Schlüssel wie für die Signierung verwenden. Erstellen Sie ein CspParameters-Objekt, und geben Sie den Namen des Schlüsselcontainers an, der für die Signierung verwendet wurde.

    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
    
  2. Rufen Sie den öffentlichen Schlüssel unter Verwendung der RSACryptoServiceProvider-Klasse ab. Der Schlüssel wird aus dem benannten Schlüsselcontainer automatisch geladen, wenn Sie das CspParameters-Objekt an den Konstruktor der RSACryptoServiceProvider-Klasse übergeben.

    Dim rsaKey As New RSACryptoServiceProvider(cspParams)
    
    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
    
  3. Erstellen Sie ein XmlDocument-Objekt, indem Sie eine XML-Datei von einem Datenträger laden. Das XmlDocument-Objekt enthält die signierten XML-Dokumente, die einer Überprüfung unterzogen werden sollen.

    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. Erstellen Sie ein neues SignedXml-Objekt, und übergeben Sie an dieses Objekt das XmlDocument-Objekt.

    Dim signedXml As New SignedXml(Doc)
    
    SignedXml signedXml = new SignedXml(Doc);
    
  5. Suchen Sie das <signature>-Element, und erstellen Sie ein neues XmlNodeList-Objekt.

    Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
    
    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
    
  6. Laden Sie die XML des ersten <signature>-Elements in das SignedXml-Objekt.

    signedXml.LoadXml(CType(nodeList(0), XmlElement))
    
    signedXml.LoadXml((XmlElement)nodeList[0]);
    
  7. Überprüfen Sie die Signatur mit der CheckSignature-Methode und dem öffentlichen RSA-Schlüssel. Diese Methode gibt einen booleschen Wert zurück, mit dem der Erfolg oder das Fehlschlagen des Vorgangs angegeben wird.

    Return signedXml.CheckSignature(Key)
    
    return signedXml.CheckSignature(Key);
    

Beispiel

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



Module VerifyXML


    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")
            ' Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...")
            Dim result As Boolean = VerifyXml(xmlDoc, rsaKey)

            ' 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 Exception
            Console.WriteLine(e.Message)
        End Try

    End Sub





    ' Verify the signature of an XML file against an asymmetric 
    ' algorithm and return the result.
    Function VerifyXml(ByVal Doc As XmlDocument, ByVal Key As RSA) As [Boolean]
        ' 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 new SignedXml object and pass it
        ' the XML document class.
        Dim signedXml As New SignedXml(Doc)
        ' Find the "Signature" node and create a new
        ' XmlNodeList object.
        Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
        ' Throw an exception if no signature was found.
        If nodeList.Count <= 0 Then
            Throw New CryptographicException("Verification failed: No Signature was found in the document.")
        End If

        ' This example only supports one signature for
        ' the entire XML document.  Throw an exception 
        ' if more than one signature was found.
        If nodeList.Count >= 2 Then
            Throw New CryptographicException("Verification failed: More that one signature was found for the document.")
        End If

        ' Load the first <signature> node.  
        signedXml.LoadXml(CType(nodeList(0), XmlElement))
        ' Check the signature and return the result.
        Return signedXml.CheckSignature(Key)
    End Function
End Module
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;

public class VerifyXML
{

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

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            bool result = VerifyXml(xmlDoc, rsaKey);

            // 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 (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }




    // Verify the signature of an XML file against an asymmetric 
    // algorithm and return the result.
    public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
    {
        // Check arguments.
        if (Doc == null)
            throw new ArgumentException("Doc");
        if (Key == null)
            throw new ArgumentException("Key");

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(Doc);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

        // Throw an exception if no signature was found.
        if (nodeList.Count <= 0)
        {
            throw new CryptographicException("Verification failed: No Signature was found in the document.");
        }

        // This example only supports one signature for
        // the entire XML document.  Throw an exception 
        // if more than one signature was found.
        if (nodeList.Count >= 2)
        {
            throw new CryptographicException("Verification failed: More that one signature was found for the document.");
        }

        // Load the first <signature> node.  
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        return signedXml.CheckSignature(Key);
    }
}

Dieses Beispiel setzt voraus, dass eine Datei mit dem Namen "test.xml" im gleichen Verzeichnis wie das kompilierte Programm vorhanden ist. Die "test.xml"-Datei muss mit den unter Gewusst wie: Signieren von XML-Dokumenten mit digitalen Signaturen beschriebenen Methoden signiert werden.

Kompilieren des Codes

Sicherheit

Speichern oder Übertragen Sie den privaten Schlüssel eines asymmetrischen Schlüsselpaares nie in Nur-Text. Weitere Informationen über symmetrische und asymmetrische, kryptografische Schlüssel finden Sie unter Erzeugen von Schlüsseln für die Ver- und Entschlüsselung.

Betten Sie einen privaten Schlüssel nie direkt in den Quellcode ein. Eingebettete Schlüssel können problemlos aus einer Assembly mithilfe von Ildasm.exe (MSIL Disassembler-Tool) oder durch Öffnen der Assembly in einem Text-Editor wie Windows Editor gelesen werden.

Siehe auch

Aufgaben

Gewusst wie: Signieren von XML-Dokumenten mit digitalen Signaturen

Referenz

System.Security.Cryptography.Xml

Weitere Ressourcen

XML-Verschlüsselung und digitale Signaturen