Share via


Como: Verifique se as assinaturas digital de documentos XML

Você pode usar as classes no System.Security.Cryptography.Xml espaço para nome para verificar os dados XML é assinado 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 verificar uma assinatura digital XML contida em um <Signature>elemento. O exemplo recupera uma chave pública RSA de um contêiner de chave e, em seguida, usa a chave para verificar a assinatura.

Para obter mais informações sobre como criar uma assinatura digital que pode ser verificada usando essa técnica, consulte Como: Assinar documentos XML com assinaturas digital.

Para verificar a assinatura digital de um documento XML

  1. Para verificar se o documento, você deve usar a mesma chave assimétrica que foi usada para assinatura.Criar um CspParameters objeto e especifique o nome do contêiner de chave que foi usado para assinatura.

    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
    
  2. Recuperar a chave pública usando o RSACryptoServiceProvider classe. A chave é carregada automaticamente do contêiner chave pelo nome, quando você passar o CspParameters objeto para o construtor das RSACryptoServiceProvider classe.

    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 documento XML assinado para verificar.

    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. Localizar o <signature>elemento e criar um novo XmlNodeList objeto.

    Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
    
    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
    
  6. Carregar o XML da primeira <signature>elemento para o SignedXml objeto.

    signedXml.LoadXml(CType(nodeList(0), XmlElement))
    
    signedXml.LoadXml((XmlElement)nodeList[0]);
    
  7. Verificar a assinatura usando o CheckSignature método e a chave pública RSA. Esse método retorna um valor booliano que indica falha ou sucesso.

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

Exemplo

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

Este exemplo assume que um arquivo chamado "test.xml" existe no mesmo diretório do programa compilado. The "test.xml" arquivo deve ser assinado usando as técnicas descritas na Como: Assinar documentos XML com assinaturas digital.

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: Assinar documentos XML com assinaturas digital

Referência

System.Security.Cryptography.Xml

Outros recursos

Assinaturas digital e criptografia XML