方法 : XML ドキュメントのデジタル署名を検証する
更新 : 2007 年 11 月
System.Security.Cryptography.Xml 名前空間のクラスを使用して、デジタル署名で署名された XML データを検証できます。XML デジタル署名 (XMLDSIG) により、署名後にデータが変更されなかったことを確認できます。XMLDSIG 標準の詳細については、http://www.w3.org/TR/xmldsig-core/ の World Wide Web Consortium (W3C) specification を参照してください。
この手順のコード例では、<Signature> 要素に含まれる XML デジタル署名を検証する方法を示します。この例では、キー コンテナから RSA 公開キーを取得し、そのキーを使用して署名を検証します。
この手法を使用して検証できるデジタル署名の作成方法については、「方法 : デジタル署名で XML ドキュメントに署名する」を参照してください。
XML ドキュメントのデジタル署名を検証するには
ドキュメントを検証するには、署名で使用されたときと同じ非対称キーを使用する必要があります。CspParameters オブジェクトを作成し、署名で使用したキー コンテナの名前を指定します。
Dim cspParams As New CspParameters() cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
RSACryptoServiceProvider クラスを使用して、公開キーを取得します。CspParameters オブジェクトを RSACryptoServiceProvider クラスのコンストラクタに渡すと、キーは名前に基づいてキー コンテナから自動的に読み込まれます。
Dim rsaKey As New RSACryptoServiceProvider(cspParams)
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
ディスクから XML ファイルをロードして、XmlDocument オブジェクトを作成します。XmlDocument オブジェクトには、検証する署名済み XML ドキュメントが含まれます。
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");
新しい SignedXml オブジェクトを作成し、それに XmlDocument オブジェクトを渡します。
Dim signedXml As New SignedXml(Doc)
SignedXml signedXml = new SignedXml(Doc);
<signature> 要素を検索し、新しい XmlNodeList オブジェクトを作成します。
Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
最初の <signature> 要素の XML を SignedXml オブジェクトに読み込みます。
signedXml.LoadXml(CType(nodeList(0), XmlElement))
signedXml.LoadXml((XmlElement)nodeList[0]);
CheckSignature メソッドおよび RSA 公開キーを使用して、署名を確認します。このメソッドは、Boolean 値を返して成功または失敗を示します。
Return signedXml.CheckSignature(Key)
return signedXml.CheckSignature(Key);
使用例
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);
}
}
この例では、"test.xml" という名前のファイルが、コンパイル済みプログラムと同じディレクトリに存在していることを前提としています。ファイル "test.xml" は、「方法 : デジタル署名で XML ドキュメントに署名する」で説明した手法を使用して署名されている必要があります。
コードのコンパイル方法
この例をコンパイルするには、System.Security.dll への参照を含める必要があります。
System.Xml、System.Security.Cryptography、および System.Security.Cryptography.Xml 名前空間を含めます。
セキュリティ
非対称キーのペアの秘密キーは、プレーンテキストで格納または転送しないでください。対称および非対称暗号キーの詳細については、「暗号化と復号化のためのキーの生成」を参照してください。
秘密キーをソース コードに直接埋め込まないでください。埋め込まれたキーは、MSIL 逆アセンブラ (Ildasm.exe) を使用したり、メモ帳などのテキスト エディタでアセンブリを開くことによって、アセンブリから簡単に読み込むことができます。
参照
処理手順
参照
System.Security.Cryptography.Xml