Share via


HOW TO:使用數位簽章簽署 XML 文件

您可以使用 System.Security.Cryptography.Xml 命名空間中的類別,以數位簽章簽署 XML 文件或部分 XML 文件。 XML 數位簽章 (XMLDSIG) 可讓您確保資料在簽署之後並未遭到修改。 如需 XMLDSIG 標準的詳細資訊,請參閱全球資訊網協會 (World Wide Web Consortium,W3C) 的 XML 簽章語法和處理 (英文) 建議。

這個程序中的程式碼範例會示範如何數位簽署整份 XML 文件,並將簽章附加到 <Signature> 項目的文件中。 此範例會建立 RSA 簽署金鑰,將此金鑰加入至安全金鑰容器,然後利用金鑰來數位簽署 XML 文件。 接著可以擷取金鑰來驗證 XML 數位簽章,或者使用金鑰來簽署其他 XML 文件。

如需有關如何驗證執行此程序所建立之 XML 數位簽章的詳細資訊,請參閱 HOW TO:驗證 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 類別的建構函式 (Constructor) 時,金鑰便會自動儲存至金鑰容器中。 這個金鑰將會用來簽署 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. 加入簽章 RSA 金鑰至 SignedXml 物件。

    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. 加入 XmlDsigEnvelopedSignatureTransform 物件至 Reference 物件。 轉換可讓驗證者使用與簽署者相同的方式來表示 XML 資料。 XML 資料可以用不同的方式來表示,因此這個步驟對驗證而言相當重要。

    Dim env As New XmlDsigEnvelopedSignatureTransform()
    reference.AddTransform(env)
    
    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);
    
  8. 加入 Reference 物件至 SignedXml 物件。

    signedXml.AddReference(reference)
    
    signedXml.AddReference(reference);
    
  9. 呼叫 ComputeSignature 方法來計算簽章。

    signedXml.ComputeSignature()
    
    signedXml.ComputeSignature();
    
  10. 擷取簽章的 XML 表示 (<Signature> 項目),並將它儲存在新的 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 的檔案。 您可以將下列 XML 放在名為 test.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 反組譯工具) 或在文字編輯器 (例如記事本) 中開啟組件,可以輕易從組件讀取內嵌金鑰。

請參閱

工作

HOW TO:驗證 XML 文件的數位簽章

參考

System.Security.Cryptography.Xml

其他資源

XML 加密和數位簽章