Share via


Como: Assinar documentos XML com assinaturas digital

Você pode usar as classes no System.Security.Cryptography.Xml namespace para assinar um documento XML ou parte de um documento XML com uma assinatura digital. Assinaturas digital XML (XMLDSIG) permitem que você verificar que dados não foi alterados após ser assinado.Para obter mais informações sobre o XMLDSIG padrão, consulte a especificação de World Wide Web Consortium (W3C) no http://www.w3.org/TR/xmldsig-core/.

O exemplo de código neste procedimento demonstra como assinar um documento XML inteiro digitalmente e anexar a assinatura ao documento em um <Signature>elemento. O exemplo cria uma chave de assinatura RSA, adiciona a chave para um contêiner de chave seguro e, em seguida, usa a chave para assinar digitalmente um documento XML.A chave, em seguida, pode ser recuperada para verificar a assinatura digital XML ou ser usada para assinar a outro documento XML.

Para obter informações sobre como verificar uma assinatura digital XML que foi criada usando este procedimento, consulte Como: Verifique se as assinaturas digital de documentos XML.

Para assinar digitalmente um documento XML

  1. Criar um CspParameters objeto e especifique o nome do contêiner de chave.

    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
    
  2. Gerar uma chave simétrica usando o RSACryptoServiceProvider classe. A chave é salvo automaticamente para o contêiner de chave quando você passar o CspParameters objeto para o construtor das RSACryptoServiceProvider classe. Essa chave será usada para assinar o documento XML.

    Dim rsaKey As New RSACryptoServiceProvider(cspParams)
    
    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
    
  3. criar an XmlDocument objeto carregando um arquivo XML do disco. The XmlDocument objeto contém o elemento XML para criptografar.

    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. Criar um novo SignedXml objeto e passar a XmlDocument objeto para ele.

    Dim signedXml As New SignedXml(Doc)
    
    SignedXml signedXml = new SignedXml(Doc);
    
  5. Adicione a chave RSA assinatura à SignedXml objeto.

    signedXml.SigningKey = Key
    
    signedXml.SigningKey = Key;
    
  6. Criar um Reference objeto que descreve o que entrar. Para assinar o documento inteiro, defina o Uri propriedade para "".

    ' 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. Adicionar um XmlDsigEnvelopedSignatureTransform objeto para o Reference objeto. Uma transformação permite que o verificador representar os dados XML da maneira idênticas que o signatário usado.Dados XML podem ser representados de maneiras diferentes, portanto, essa etapa é vital para verificação.

    Dim env As New XmlDsigEnvelopedSignatureTransform()
    reference.AddTransform(env)
    
    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);
    
  8. Adicionar o Reference objeto para o SignedXml objeto.

    signedXml.AddReference(reference)
    
    signedXml.AddReference(reference);
    
  9. A assinatura de computação, chamando o ComputeSignature método.

    signedXml.ComputeSignature()
    
    signedXml.ComputeSignature();
    
  10. Recuperar a representação XML da assinatura (um <Signature>elemento) e salvá-lo em um novo XmlElement objeto.

    Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
    
    XmlElement xmlDigitalSignature = signedXml.GetXml();
    
  11. Acrescentar elemento o XmlDocument objeto.

    Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, True))
    
    Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
    
  12. salvar o documento.

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

Exemplo

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

    }
}

Este exemplo assume que um arquivo chamado "test.xml" existe no mesmo diretório do programa compilado. Você pode colocar o XML a seguir em um arquivo denominado test.xml e usá-lo com esse exemplo.

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

Compilando o código

Segurança

Nunca armazene ou transferência a chave particular de um emparelhar de chaves assimétricas em texto não criptografado.Para obter mais informações sobre chaves de criptografia simétricas e assimétricas, consulte Gerando chaves de criptografia e descriptografia.

Nunca incorpore uma chave particular diretamente no seu código-fonte.Chaves incorporadas podem ser lido com com facilidade de um assembly usando o Desassemblador do MSIL (ILDASM.exe) ou abrindo o assembly em um editor de texto, sistema autônomo o bloco de notas.

Consulte também

Tarefas

Como: Verifique se as assinaturas digital de documentos XML

Referência

System.Security.Cryptography.Xml

Outros recursos

Assinaturas digital e criptografia XML