Nasıl yapılır: XML Belgelerinin Dijital İmzalarını Doğrulama

Dijital imzayla imzalanan XML verilerini doğrulamak için ad alanında sınıfları System.Security.Cryptography.Xml kullanabilirsiniz. XML dijital imzaları (XMLDSIG), verilerin imzalandıktan sonra değiştirilmediğini doğrulamanıza olanak sağlar. XMLDSIG standardı hakkında daha fazla bilgi için, konumundaki https://www.w3.org/TR/xmldsig-core/World Wide Web Consortium (W3C) belirtimine bakın.

Not

Bu makaledeki kod Windows için geçerlidir.

Bu yordamdaki kod örneği, bir öğenin içerdiği <Signature> XML dijital imzasını doğrulamayı gösterir. Örnek, bir anahtar kapsayıcısından bir RSA ortak anahtarı alır ve ardından imzayı doğrulamak için anahtarı kullanır.

Bu teknik kullanılarak doğrulanabilir bir dijital imza oluşturma hakkında bilgi için bkz . Nasıl yapılır: XML Belgelerini Dijital İmzalarla İmzala.

Bir XML belgesinin dijital imzasını doğrulamak için

  1. Belgeyi doğrulamak için, imzalama için kullanılan aynı asimetrik anahtarı kullanmanız gerekir. Bir CspParameters nesne oluşturun ve imzalama için kullanılan anahtar kapsayıcısının adını belirtin.

    CspParameters cspParams = new()
    {
        KeyContainerName = "XML_DSIG_RSA_KEY"
    };
    
    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
    
  2. sınıfını kullanarak RSACryptoServiceProvider ortak anahtarı alın. Nesnesini sınıfın oluşturucusundan RSACryptoServiceProvider geçirdiğinizde CspParameters anahtar, anahtar kapsayıcısından ada göre otomatik olarak yüklenir.

    RSACryptoServiceProvider rsaKey = new(cspParams);
    
    Dim rsaKey As New RSACryptoServiceProvider(cspParams)
    
  3. Diskten xml XmlDocument dosyası yükleyerek bir nesne oluşturun. XmlDocument nesnesi, doğrulanması gereken imzalı XML belgesini içerir.

    XmlDocument xmlDoc = new()
    {
        // Load an XML file into the XmlDocument object.
        PreserveWhitespace = true
    };
    xmlDoc.Load("test.xml");
    
    Dim xmlDoc As New XmlDocument()
    
    ' Load an XML file into the XmlDocument object.
    xmlDoc.PreserveWhitespace = True
    xmlDoc.Load("test.xml")
    
  4. Yeni SignedXml bir nesne oluşturun ve nesneyi ona geçirin XmlDocument .

    SignedXml signedXml = new(xmlDoc);
    
    Dim signedXml As New SignedXml(xmlDoc)
    
  5. <>signatureöğesini bulun ve yeni XmlNodeList bir nesne oluşturun.

    XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");
    
    Dim nodeList As XmlNodeList = xmlDoc.GetElementsByTagName("Signature")
    
  6. İlk <signature> öğenin XML'sini nesnesine SignedXml yükleyin.

    signedXml.LoadXml((XmlElement?)nodeList[0]);
    
    signedXml.LoadXml(CType(nodeList(0), XmlElement))
    
  7. yöntemini ve RSA ortak anahtarını kullanarak CheckSignature imzayı denetleyin. Bu yöntem, başarıyı veya başarısızlığı gösteren bir Boole değeri döndürür.

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

Örnek

Bu örnekte, adlı "test.xml" bir dosyanın derlenen programla aynı dizinde mevcut olduğu varsayılır. Dosya, "test.xml" Nasıl yapılır: XML Belgelerini Dijital İmzalarla İmzala başlığı altında açıklanan teknikler kullanılarak imzalanmalıdır.

using System;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;

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

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

            // Create a new XML document.
            XmlDocument xmlDoc = new()
            {
                // Load an XML file into the XmlDocument object.
                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 bool VerifyXml(XmlDocument xmlDoc, RSA key)
    {
        // Check arguments.
        if (xmlDoc == null)
             throw new ArgumentException(null, nameof(xmlDoc));
        if (key == null)
            throw new ArgumentException(null, nameof(key));

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

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDoc.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);
    }
}
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 xmlDoc As XmlDocument, ByVal key As RSA) As [Boolean]
        ' Check arguments.
        If xmlDoc Is Nothing Then
            Throw New ArgumentException(
                "The XML doc cannot be nothing.", NameOf(xmlDoc))
        End If
        If key Is Nothing Then
            Throw New ArgumentException(
                "The key cannot be nothing.", NameOf(key))
        End If
        ' Create a new SignedXml object and pass it
        ' the XML document class.
        Dim signedXml As New SignedXml(xmlDoc)
        ' Find the "Signature" node and create a new
        ' XmlNodeList object.
        Dim nodeList As XmlNodeList = xmlDoc.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

Kod Derleniyor

.NET Güvenliği

Asimetrik anahtar çiftinin özel anahtarını hiçbir zaman düz metin olarak depolamayın veya aktarmayın. Simetrik ve asimetrik şifreleme anahtarları hakkında daha fazla bilgi için bkz . Şifreleme ve Şifre Çözme için Anahtar Oluşturma.

Özel anahtarı hiçbir zaman doğrudan kaynak kodunuz içine eklemeyin. Katıştırılmış anahtarlar, Ildasm.exe (IL Disassembler) kullanılarak veya derlemeyi Not Defteri gibi bir metin düzenleyicisinde açarak bir derlemeden kolayca okunabilir.

Ayrıca bkz.