方法 : デジタル署名で XML ドキュメントに署名する
更新 : 2007 年 11 月
System.Security.Cryptography.Xml 名前空間のクラスを使用すると、XML ドキュメントまたは XML ドキュメントの一部にデジタル署名で署名できます。XML デジタル署名 (XMLDSIG) により、署名後にデータが変更されなかったことを確認できます。XMLDSIG 標準の詳細については、http://www.w3.org/TR/xmldsig-core/ の World Wide Web Consortium (W3C) specification を参照してください。
この手順のコード例では、XML ドキュメント全体にデジタル署名する方法や、<Signature> 要素のドキュメントに署名を適用する方法を示します。この例では、RSA 署名キーを作成し、キーを安全なキー コンテナに追加し、キーを使用して XML ドキュメントにデジタル署名します。その後、このキーを使用して、XML デジタル署名を検証するために取得したり、別の XML ドキュメントに署名したりできます。
この手順を使用して作成された XML デジタル署名を検証する方法については、「方法 : 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 クラスのコンストラクタに渡すと、キーがキー コンテナに自動的に保存されます。このキーは、XML ドキュメントに署名するために使用されます。
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);
SignedXml オブジェクトに、署名する RSA キーを追加します。
signedXml.SigningKey = Key
signedXml.SigningKey = Key;
署名の内容を示す Reference オブジェクトを作成します。ドキュメント全体に署名するには、Uri プロパティを "" に設定します。
' 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 = "";
Reference オブジェクトに XmlDsigEnvelopedSignatureTransform オブジェクトを追加します。変換により、検証者は署名者が使用したのと同じ方法で XML データを表すことができます。XML データは複数の方法で表されることがあるため、この手順は検証のために不可欠です。
Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env)
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env);
SignedXml オブジェクトに Reference オブジェクトを追加します。
signedXml.AddReference(reference)
signedXml.AddReference(reference);
ComputeSignature メソッドを呼び出して、署名を計算します。
signedXml.ComputeSignature()
signedXml.ComputeSignature();
署名 (<Signature> 要素) の XML 形式のデータを取得して、新しい XmlElement オブジェクトに追加します。
Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
XmlElement xmlDigitalSignature = signedXml.GetXml();
XmlDocument オブジェクトに要素を追加します。
Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, True))
Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
ドキュメントを保存します。
xmlDoc.Save("test.xml")
xmlDoc.Save("test.xml");
使用例
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));
}
}
この例では、"test.xml" という名前のファイルが、コンパイル済みプログラムと同じディレクトリに存在していることを前提としています。test.xml という名前のファイルに次の XML を配置し、その XML をこの例と共に使用できます。
<root>
<creditcard>
<number>19834209</number>
<expiry>02/02/2002</expiry>
</creditcard>
</root>
コードのコンパイル方法
この例をコンパイルするには、System.Security.dll への参照を含める必要があります。
System.Xml、System.Security.Cryptography、および System.Security.Cryptography.Xml 名前空間を含めます。
セキュリティ
非対称キーのペアの秘密キーは、プレーンテキストで格納または転送しないでください。対称および非対称暗号キーの詳細については、「暗号化と復号化のためのキーの生成」を参照してください。
秘密キーをソース コードに直接埋め込まないでください。埋め込まれたキーは、MSIL 逆アセンブラ (Ildasm.exe) を使用したり、メモ帳などのテキスト エディタでアセンブリを開くことによって、アセンブリから簡単に読み込むことができます。
参照
処理手順
参照
System.Security.Cryptography.Xml