次の方法で共有


方法 : デジタル署名で XML ドキュメントに署名する

System.Security.Cryptography.Xml 名前空間のクラスを使用すると、XML ドキュメントまたは XML ドキュメントの一部にデジタル署名で署名できます。 XML デジタル署名 (XMLDSIG) により、署名後にデータが変更されなかったことを確認できます。 XMLDSIG 標準の詳細については、W3C (World Wide Web Consortium) 勧告「XML Signature Syntax and Processing」を参照してください。

この手順のコード例では、XML ドキュメント全体にデジタル署名する方法や、<Signature> 要素のドキュメントに署名を適用する方法を示します。 この例では、RSA 署名キーを作成し、キーを安全なキー コンテナーに追加し、キーを使用して XML ドキュメントにデジタル署名します。 その後、このキーを使用して、XML デジタル署名を検証するために取得したり、別の XML ドキュメントに署名したりできます。

この手順を使用して作成された XML デジタル署名を検証する方法については、「方法 : XML ドキュメントのデジタル署名を検証する」を参照してください。

XML ドキュメントにデジタル署名するには

  1. CspParameters オブジェクトを作成し、キー コンテナーの名前を指定します。

    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
    
  2. RSACryptoServiceProvider クラスを使用して非対称キーを生成します。 CspParameters オブジェクトを RSACryptoServiceProvider クラスのコンストラクターに渡すと、キーがキー コンテナーに自動的に保存されます。 このキーは、XML ドキュメントに署名するために使用されます。

    Dim rsaKey As New RSACryptoServiceProvider(cspParams)
    
    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
    
  3. ディスクから 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");
    
  4. 新しい SignedXml オブジェクトを作成し、それに XmlDocument オブジェクトを渡します。

    Dim signedXml As New SignedXml(xmlDoc)
    
    SignedXml signedXml = new SignedXml(xmlDoc);
    
  5. SignedXml オブジェクトに、署名する RSA キーを追加します。

    signedXml.SigningKey = Key
    
    signedXml.SigningKey = Key;
    
  6. 署名の内容を示す 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 = "";
    
  7. Reference オブジェクトに XmlDsigEnvelopedSignatureTransform オブジェクトを追加します。 変換により、検証者は署名者が使用したのと同じ方法で XML データを表すことができます。 XML データは複数の方法で表されることがあるため、この手順は検証のために不可欠です。

    Dim env As New XmlDsigEnvelopedSignatureTransform()
    reference.AddTransform(env)
    
    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);
    
  8. SignedXml オブジェクトに Reference オブジェクトを追加します。

    signedXml.AddReference(reference)
    
    signedXml.AddReference(reference);
    
  9. ComputeSignature メソッドを呼び出して、署名を計算します。

    signedXml.ComputeSignature()
    
    signedXml.ComputeSignature();
    
  10. 署名 (<Signature> 要素) の XML 形式のデータを取得して、新しい XmlElement オブジェクトに追加します。

    Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
    
    XmlElement xmlDigitalSignature = signedXml.GetXml();
    
  11. XmlDocument オブジェクトに要素を追加します。

    xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, True))
    
    xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
    
  12. ドキュメントを保存します。

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

使用例

この例では、test.xml という名前のファイルが、コンパイル済みプログラムと同じディレクトリに存在していることを前提としています。 test.xml という名前のファイルに次の XML を配置し、その XML をこの例と共に使用できます。

<root>
    <creditcard>
        <number>19834209</number>
        <expiry>02/02/2002</expiry>
    </creditcard>
</root>
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 xmlDoc As XmlDocument, ByVal Key As RSA)
        ' 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 SignedXml object.
        Dim signedXml As New SignedXml(xmlDoc)
        ' 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.
        xmlDoc.DocumentElement.AppendChild(xmlDoc.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 xmlDoc, RSA Key)
    {
        // Check arguments.
        if (xmlDoc == null)
            throw new ArgumentException("xmlDoc");
        if (Key == null)
            throw new ArgumentException("Key");

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(xmlDoc);

        // 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.
        xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

    }
}

コードのコンパイル

セキュリティ

非対称キーのペアの秘密キーは、プレーンテキストで格納または転送しないでください。 対称および非対称暗号キーの詳細については、「暗号化と復号化のためのキーの生成」を参照してください。

秘密キーをソース コードに直接埋め込まないでください。 埋め込まれたキーは、Ildasm.exe (MSIL 逆アセンブラー) を使用したり、メモ帳などのテキスト エディターでアセンブリを開くことによって、アセンブリから簡単に読み込むことができます。

参照

処理手順

方法 : XML ドキュメントのデジタル署名を検証する

参照

System.Security.Cryptography.Xml

その他の技術情報

XML 暗号化と XML デジタル署名