方法: XML ドキュメントのデジタル署名を検証するHow to: Verify the Digital Signatures of XML Documents

System.Security.Cryptography.Xml 名前空間にあるクラスを使用すると、デジタル署名で署名された XML データを検証できます。You can use the classes in the System.Security.Cryptography.Xml namespace to verify XML data signed with a digital signature. XML デジタル署名 (XMLDSIG) を使用すると、データが署名後に変更されなかったことを確認できます。XML digital signatures (XMLDSIG) allow you to verify that data was not altered after it was signed. XMLDSIG 標準の詳細についてにある World Wide Web Consortium (W3C) 仕様を参照して https://www.w3.org/TR/xmldsig-core/ です。For more information about the XMLDSIG standard, see the World Wide Web Consortium (W3C) specification at https://www.w3.org/TR/xmldsig-core/.

この手順のコード例に含まれている XML デジタル署名を確認する方法を示します、<Signature> 要素。The code example in this procedure demonstrates how to verify an XML digital signature contained in a <Signature> element. この例では、キー コンテナーから RSA 公開キーを取得してから、キーを使用して署名を確認します。The example retrieves an RSA public key from a key container and then uses the key to verify the signature.

この手法を使用して検証できるデジタル署名を作成する方法についてを参照してください。方法。デジタル署名で XML ドキュメントします。For information about how create a digital signature that can be verified using this technique, see How to: Sign XML Documents with Digital Signatures.

XML ドキュメントのデジタル署名を検証するにはTo verify the digital signature of an XML document

  1. ドキュメントを検証するには、署名に使用した非対称キーと同じ非対称キーを使用する必要があります。To verify the document, you must use the same asymmetric key that was used for signing. CspParameters オブジェクトを作成し、署名に使用したキー コンテナーの名前を指定します。Create a CspParameters object and specify the name of the key container that was used for signing.

    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
    
    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
    
  2. RSACryptoServiceProvider クラスを使用して公開キーを取得します。Retrieve the public key using the RSACryptoServiceProvider class. CspParameters オブジェクトを RSACryptoServiceProvider クラスのコンストラクターに渡すと、キー コンテナーからキーが名前順で自動的に読み込まれます。The key is automatically loaded from the key container by name when you pass the CspParameters object to the constructor of the RSACryptoServiceProvider class.

    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
    
    Dim rsaKey As New RSACryptoServiceProvider(cspParams)
    
  3. ディスクから XML ファイルを読み込んで XmlDocument オブジェクトを作成します。Create an XmlDocument object by loading an XML file from disk. XmlDocument オブジェクトには、確認対象の署名済みの XML ドキュメントが含まています。The XmlDocument object contains the signed XML document to verify.

    XmlDocument xmlDoc = new XmlDocument();
    
    // Load an XML file into the XmlDocument object.
    xmlDoc.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. SignedXml オブジェクトを新規作成し、それに XmlDocument オブジェクトを渡します。Create a new SignedXml object and pass the XmlDocument object to it.

    SignedXml signedXml = new SignedXml(xmlDoc);
    
    Dim signedXml As New SignedXml(xmlDoc)
    
  5. 検索、<signature> 要素を新規作成およびXmlNodeListオブジェクト。Find the <signature> element and create a new XmlNodeList object.

    XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");
    
    Dim nodeList As XmlNodeList = xmlDoc.GetElementsByTagName("Signature")
    
  6. 最初の XML を読み込む <signature> 要素に、SignedXmlオブジェクト。Load the XML of the first <signature> element into the SignedXml object.

    signedXml.LoadXml((XmlElement)nodeList[0]);
    
    signedXml.LoadXml(CType(nodeList(0), XmlElement))
    
  7. CheckSignature メソッドと RSA の公開キーを使用して署名を確認します。Check the signature using the CheckSignature method and the RSA public key. このメソッドは、成功または失敗を示すブール値を返します。This method returns a Boolean value that indicates success or failure.

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

Example

この例では、"test.xml" という名前のファイルがコンパイル済みのプログラムと同じディレクトリに存在することを前提としています。This example assumes that a file named "test.xml" exists in the same directory as the compiled program. "test.xml"で説明する手法を使用してファイルを署名する必要があります方法。デジタル署名で XML ドキュメントします。The "test.xml" file must be signed using the techniques described in How to: Sign XML Documents with Digital Signatures.

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

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(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("xmlDoc")
        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(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

コードのコンパイルCompiling the Code

.NET Framework セキュリティ.NET Framework Security

非対称キー ペアの秘密キーをプレーンテキストで保存または転送しないでください。Never store or transfer the private key of an asymmetric key pair in plaintext. 対称暗号化キーと非対称暗号化キーの詳細については、暗号化と復号化キーを生成するを参照してください。For more information about symmetric and asymmetric cryptographic keys, see Generating Keys for Encryption and Decryption.

秘密キーをソース コードに直接埋め込まないでください。Never embed a private key directly into your source code. 埋め込まれたキーは、アセンブリをIldasm.exe (IL 逆アセンブラー)またはメモ帳などのテキスト エディターで開くことで、簡単に読み取ることができます。Embedded keys can be easily read from an assembly using the Ildasm.exe (IL Disassembler) or by opening the assembly in a text editor such as Notepad.

関連項目See also