Nasıl yapılır: XML Belgelerini Dijital İmzalarla imzalama

Xml belgesini veya XML belgesinin System.Security.Cryptography.Xml bir bölümünü dijital imzayla imzalamak için ad alanında sınıfları 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 bkz. World Wide Web Consortium (W3C) önerisi XML İmza Söz Dizimi ve İşleme.

Not

Bu makaledeki kod Windows için geçerlidir.

Bu yordamdaki kod örneği, bir XML belgesinin tamamını dijital olarak imzalamayı ve bir öğedeki <Signature> belgeye imza eklemeyi gösterir. Örnek bir RSA imzalama anahtarı oluşturur, anahtarı güvenli bir anahtar kapsayıcısına ekler ve ardından anahtarı kullanarak bir XML belgesini dijital olarak imzalar. Anahtar daha sonra XML dijital imzasını doğrulamak için alınabilir veya başka bir XML belgesi imzalamak için kullanılabilir.

Bu yordam kullanılarak oluşturulan bir XML dijital imzasını doğrulama hakkında bilgi için bkz . Nasıl yapılır: XML Belgelerinin Dijital İmzalarını Doğrulama.

XML belgesini dijital olarak imzalamak için

  1. Bir CspParameters nesne oluşturun ve anahtar kapsayıcısının adını belirtin.

    CspParameters cspParams = new()
    {
        KeyContainerName = "XML_DSIG_RSA_KEY"
    };
    
    Dim cspParams As New CspParameters With {
        .KeyContainerName = "XML_DSIG_RSA_KEY"
    }
    
  2. sınıfını RSACryptoServiceProvider kullanarak asimetrik bir anahtar oluşturun. nesnesini sınıfın oluşturucusunun öğesine geçirdiğinizde CspParameters anahtar otomatik olarak anahtar kapsayıcısına RSACryptoServiceProvider kaydedilir. Bu anahtar, XML belgesini imzalamak için kullanılır.

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

    XmlDocument xmlDoc = new()
    {
        // Load an XML file into the XmlDocument object.
        PreserveWhitespace = true
    };
    xmlDoc.Load("test.xml");
    
    ' Load an XML file into the XmlDocument object.
    Dim xmlDoc As New XmlDocument With {
        .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. İmzalama RSA anahtarını nesnesine SignedXml ekleyin.

        SigningKey = rsaKey
    };
    
    signedXml.SigningKey = rsaKey
    
  6. Nelerin imzalandığını açıklayan bir Reference nesne oluşturun. Belgenin tamamını imzalamak için özelliğini olarak ""ayarlayınUri.

    // Create a reference to be signed.
    Reference reference = new()
    {
        Uri = ""
    };
    
    ' Create a reference to be signed.
    Dim reference As New Reference()
    reference.Uri = ""
    
  7. Nesneye Reference bir XmlDsigEnvelopedSignatureTransform nesne ekleyin. Dönüştürme, doğrulayıcının XML verilerini imzalayanın kullandığı şekilde temsil etmesini sağlar. XML verileri farklı şekillerde gösterilebilir, bu nedenle bu adım doğrulama için çok önemlidir.

    XmlDsigEnvelopedSignatureTransform env = new();
    reference.AddTransform(env);
    
    Dim env As New XmlDsigEnvelopedSignatureTransform()
    reference.AddTransform(env)
    
  8. Reference nesnesini nesnesine SignedXml ekleyin.

    signedXml.AddReference(reference);
    
    signedXml.AddReference(reference)
    
  9. yöntemini çağırarak imzayı hesaplar ComputeSignature .

    signedXml.ComputeSignature();
    
    signedXml.ComputeSignature()
    
  10. İmzanın XML gösterimini (bir <Signature> öğe) alın ve yeni XmlElement bir nesneye kaydedin.

    XmlElement xmlDigitalSignature = signedXml.GetXml();
    
    Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
    
  11. öğesini nesnesine XmlDocument ekleyin.

    xmlDoc.DocumentElement?.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    
    xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, True))
    
  12. Belgeyi kaydedin.

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

Örnek

Bu örnekte, adlı test.xml bir dosyanın derlenen programla aynı dizinde mevcut olduğu varsayılır. Aşağıdaki XML'yi adlı test.xml bir dosyaya yerleştirebilir ve bu örnekle kullanabilirsiniz.

<root>  
    <creditcard>  
        <number>19834209</number>  
        <expiry>02/02/2002</expiry>  
    </creditcard>  
</root>  
using System;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;

[SupportedOSPlatform("Windows")]
public class SignXML
{
    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");

            // 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 xmlDoc, RSA rsaKey)
    {
        // Check arguments.
        if (xmlDoc == null)
            throw new ArgumentException(null, nameof(xmlDoc));
        if (rsaKey == null)
            throw new ArgumentException(null, nameof(rsaKey));

        // Create a SignedXml object.
        SignedXml signedXml = new(xmlDoc)
        {

            // Add the key to the SignedXml document.
            SigningKey = rsaKey
        };

        // Create a reference to be signed.
        Reference reference = new()
        {
            Uri = ""
        };

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new();
        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.
        xmlDoc.DocumentElement?.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    }
}
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 With {
                .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.
            ' Load an XML file into the XmlDocument object.
            Dim xmlDoc As New XmlDocument With {
                .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 xmlDoc As XmlDocument, ByVal rsaKey As RSA)
        ' Check arguments.
        If xmlDoc Is Nothing Then
            Throw New ArgumentException(
                "The XML doc cannot be nothing.", NameOf(xmlDoc))
        End If
        If rsaKey Is Nothing Then
            Throw New ArgumentException(
                "The RSA key cannot be nothing.", NameOf(rsaKey))
        End If
        ' Create a SignedXml object.
        Dim signedXml As New SignedXml(xmlDoc)
        ' Add the key to the SignedXml document.
        signedXml.SigningKey = rsaKey
        ' 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.
        xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, True))
    End Sub
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.