共用方式為


HOW TO:使用對稱金鑰加密 XML 項目

您可以使用 System.Security.Cryptography.Xml 命名空間中的類別,加密 XML 文件中的項目。 XML 加密能讓您儲存或傳輸機密的 XML,而不需擔心資料會輕易遭到讀取。 這個程序會使用 Advanced Encryption Standard (AES) 演算法 (也稱為 Rijndael 演算法) 解密 XML 項目。

如需有關如何解密以此程序加密之 XML 項目的詳細資訊,請參閱 HOW TO:使用對稱金鑰解密 XML 項目

使用對稱演算法 (如 AES) 加密 XML 資料時,您必須使用同一個金鑰來加密和解密 XML 資料。 這個程序中的範例假設加密的 XML 將使用相同的金鑰來進行解密,且加密和解密的兩方在使用的演算法和金鑰方面已取得共識。 這個範例並未在加密的 XML 內儲存或加密 AES 金鑰。

這個範例適用於當單一應用程式需要根據儲存在記憶體中的工作階段金鑰來加密資料,或是根據從密碼衍生的密碼編譯強式金鑰來加密資料的情況。 在兩個以上的應用程式都需要共用加密 XML 資料的情況下,您可以考慮使用以非對稱演算法或 X.509 憑證為基礎的加密配置。

若要使用對稱金鑰加密 XML 項目

  1. 使用 RijndaelManaged 類別產生對稱金鑰。 這個金鑰將會用來加密 XML 項目。

    Dim key As RijndaelManaged = Nothing
    
    Try
        ' Create a new Rijndael key.
        key = New RijndaelManaged()
    
                RijndaelManaged key = null;
    
                try
                {
                    // Create a new Rijndael key.
                    key = new RijndaelManaged();
    
  2. 從磁碟載入 XML 檔案,建立 XmlDocument 物件。 XmlDocument 物件包含要加密的 XML 項目。

    ' Load an XML document.
    Dim xmlDoc As New XmlDocument()
    xmlDoc.PreserveWhitespace = True
    xmlDoc.Load("test.xml")
    
                    // Load an XML document.
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load("test.xml");
    
  3. XmlDocument 物件中尋找指定的項目,並建立新的 XmlElement 物件以表示您要加密的項目。 在這個範例中,"creditcard" 項目已加密。

    Dim elementToEncrypt As XmlElement = Doc.GetElementsByTagName(ElementName)(0)
    
                XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
    
  4. 建立 EncryptedXml 類別的新執行個體,並利用該執行個體來使用對稱金鑰來加密 XmlElementEncryptData 方法會將加密的項目傳回為加密位元組陣列。

    Dim eXml As New EncryptedXml()
    
    Dim encryptedElement As Byte() = eXml.EncryptData(elementToEncrypt, Key, False)
    
                EncryptedXml eXml = new EncryptedXml();
    
                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
    
  5. 建構 EncryptedData 物件,並在其中填入 XML 加密項目的 URL 識別項。 這個 URL 識別項能讓解密的一方得知 XML 中含有加密的項目。 您可以使用 XmlEncElementUrl 欄位指定 URL 識別項。

    Dim edElement As New EncryptedData()
    edElement.Type = EncryptedXml.XmlEncElementUrl
    
                EncryptedData edElement = new EncryptedData();
                edElement.Type = EncryptedXml.XmlEncElementUrl;
    
  6. 建立 EncryptionMethod 物件,此物件會初始化成為用來產生金鑰之密碼編譯演算法的 URL 識別項。 傳遞 EncryptionMethod 物件至 EncryptionMethod 屬性。

    Dim encryptionMethod As String = Nothing
    
    If TypeOf Key Is TripleDES Then
        encryptionMethod = EncryptedXml.XmlEncTripleDESUrl
    ElseIf TypeOf Key Is DES Then
        encryptionMethod = EncryptedXml.XmlEncDESUrl
    End If
    If TypeOf Key Is Rijndael Then
        Select Case Key.KeySize
            Case 128
                encryptionMethod = EncryptedXml.XmlEncAES128Url
            Case 192
                encryptionMethod = EncryptedXml.XmlEncAES192Url
            Case 256
                encryptionMethod = EncryptedXml.XmlEncAES256Url
        End Select
    Else
        ' Throw an exception if the transform is not in the previous categories
        Throw New CryptographicException("The specified algorithm is not supported for XML Encryption.")
    End If
    
    edElement.EncryptionMethod = New EncryptionMethod(encryptionMethod)
    
                string encryptionMethod = null;
    
                if (Key is TripleDES)
                {
                    encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
                }
                else if (Key is DES)
                {
                    encryptionMethod = EncryptedXml.XmlEncDESUrl;
                }
                if (Key is Rijndael)
                {
                    switch (Key.KeySize)
                    {
                        case 128:
                            encryptionMethod = EncryptedXml.XmlEncAES128Url;
                            break;
                        case 192:
                            encryptionMethod = EncryptedXml.XmlEncAES192Url;
                            break;
                        case 256:
                            encryptionMethod = EncryptedXml.XmlEncAES256Url;
                            break;
                    }
                }
                else
                {
                    // Throw an exception if the transform is not in the previous categories
                    throw new CryptographicException("The specified algorithm is not supported for XML Encryption.");
                }
    
                edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
    
  7. 加入加密的項目資料至 EncryptedData 物件。

    edElement.CipherData.CipherValue = encryptedElement
    
                edElement.CipherData.CipherValue = encryptedElement;
    
  8. 將項目從原始的 XmlDocument 物件取代為 EncryptedData 項目。

    EncryptedXml.ReplaceElement(elementToEncrypt, edElement, False)
    
                EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
    

範例

Imports System
Imports System.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml




Module Program

    Sub Main(ByVal args() As String)
        Dim key As RijndaelManaged = Nothing

        Try
            ' Create a new Rijndael key.
            key = New RijndaelManaged()
            ' Load an XML document.
            Dim xmlDoc As New XmlDocument()
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
            ' Encrypt the "creditcard" element.
            Encrypt(xmlDoc, "creditcard", key)

            Console.WriteLine("The element was encrypted")

            Console.WriteLine(xmlDoc.InnerXml)

            Decrypt(xmlDoc, key)

            Console.WriteLine("The element was decrypted")

            Console.WriteLine(xmlDoc.InnerXml)


        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally
            ' Clear the key.
            If Not (key Is Nothing) Then
                key.Clear()
            End If
        End Try

    End Sub


    Sub Encrypt(ByVal Doc As XmlDocument, ByVal ElementName As String, ByVal Key As SymmetricAlgorithm)
        ' Check the arguments.  
        If Doc Is Nothing Then
            Throw New ArgumentNullException("Doc")
        End If
        If ElementName Is Nothing Then
            Throw New ArgumentNullException("ElementToEncrypt")
        End If
        If Key Is Nothing Then
            Throw New ArgumentNullException("Alg")
        End If
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Find the specified element in the XmlDocument
        ' object and create a new XmlElemnt object.
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim elementToEncrypt As XmlElement = Doc.GetElementsByTagName(ElementName)(0)

        ' Throw an XmlException if the element was not found.
        If elementToEncrypt Is Nothing Then
            Throw New XmlException("The specified element was not found")
        End If

        ''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Create a new instance of the EncryptedXml class 
        ' and use it to encrypt the XmlElement with the 
        ' symmetric key.
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim eXml As New EncryptedXml()

        Dim encryptedElement As Byte() = eXml.EncryptData(elementToEncrypt, Key, False)
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Construct an EncryptedData object and populate
        ' it with the desired encryption information.
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim edElement As New EncryptedData()
        edElement.Type = EncryptedXml.XmlEncElementUrl
        ' Create an EncryptionMethod element so that the 
        ' receiver knows which algorithm to use for decryption.
        ' Determine what kind of algorithm is being used and
        ' supply the appropriate URL to the EncryptionMethod element.
        Dim encryptionMethod As String = Nothing

        If TypeOf Key Is TripleDES Then
            encryptionMethod = EncryptedXml.XmlEncTripleDESUrl
        ElseIf TypeOf Key Is DES Then
            encryptionMethod = EncryptedXml.XmlEncDESUrl
        End If
        If TypeOf Key Is Rijndael Then
            Select Case Key.KeySize
                Case 128
                    encryptionMethod = EncryptedXml.XmlEncAES128Url
                Case 192
                    encryptionMethod = EncryptedXml.XmlEncAES192Url
                Case 256
                    encryptionMethod = EncryptedXml.XmlEncAES256Url
            End Select
        Else
            ' Throw an exception if the transform is not in the previous categories
            Throw New CryptographicException("The specified algorithm is not supported for XML Encryption.")
        End If

        edElement.EncryptionMethod = New EncryptionMethod(encryptionMethod)
        ' Add the encrypted element data to the 
        ' EncryptedData object.
        edElement.CipherData.CipherValue = encryptedElement
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Replace the element from the original XmlDocument
        ' object with the EncryptedData element.
        ''''''''''''''''''''''''''''''''''''''''''''''''''
        EncryptedXml.ReplaceElement(elementToEncrypt, edElement, False)

    End Sub 'Encrypt


    Sub Decrypt(ByVal Doc As XmlDocument, ByVal Alg As SymmetricAlgorithm)
        ' Check the arguments.  
        If Doc Is Nothing Then
            Throw New ArgumentNullException("Doc")
        End If
        If Alg Is Nothing Then
            Throw New ArgumentNullException("Alg")
        End If
        ' Find the EncryptedData element in the XmlDocument.
        Dim encryptedElement As XmlElement = Doc.GetElementsByTagName("EncryptedData")(0)

        ' If the EncryptedData element was not found, throw an exception.
        If encryptedElement Is Nothing Then
            Throw New XmlException("The EncryptedData element was not found.")
        End If


        ' Create an EncryptedData object and populate it.
        Dim edElement As New EncryptedData()
        edElement.LoadXml(encryptedElement)
        ' Create a new EncryptedXml object.
        Dim exml As New EncryptedXml()


        ' Decrypt the element using the symmetric key.
        Dim rgbOutput As Byte() = exml.DecryptData(edElement, Alg)
        ' Replace the encryptedData element with the plaintext XML element.
        exml.ReplaceData(encryptedElement, rgbOutput)
    End Sub
End Module

using System;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;


namespace CSCrypto
{
    class Program
    {
        static void Main(string[] args)
        {
            RijndaelManaged key = null;

            try
            {
                // Create a new Rijndael key.
                key = new RijndaelManaged();
                // Load an XML document.
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load("test.xml");

                // Encrypt the "creditcard" element.
                Encrypt(xmlDoc, "creditcard", key);

                Console.WriteLine("The element was encrypted");

                Console.WriteLine(xmlDoc.InnerXml);

                Decrypt(xmlDoc, key);

                Console.WriteLine("The element was decrypted");

                Console.WriteLine(xmlDoc.InnerXml);

                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // Clear the key.
                if (key != null)
                {
                    key.Clear();
                }
            }

        }

        public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key)
        {
            // Check the arguments.  
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (ElementName == null)
                throw new ArgumentNullException("ElementToEncrypt");
            if (Key == null)
                throw new ArgumentNullException("Alg");

            ////////////////////////////////////////////////
            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            ////////////////////////////////////////////////
            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");

            }

            //////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class 
            // and use it to encrypt the XmlElement with the 
            // symmetric key.
            //////////////////////////////////////////////////

            EncryptedXml eXml = new EncryptedXml();

            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
            ////////////////////////////////////////////////
            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            ////////////////////////////////////////////////

            EncryptedData edElement = new EncryptedData();
            edElement.Type = EncryptedXml.XmlEncElementUrl;

            // Create an EncryptionMethod element so that the 
            // receiver knows which algorithm to use for decryption.
            // Determine what kind of algorithm is being used and
            // supply the appropriate URL to the EncryptionMethod element.

            string encryptionMethod = null;

            if (Key is TripleDES)
            {
                encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
            }
            else if (Key is DES)
            {
                encryptionMethod = EncryptedXml.XmlEncDESUrl;
            }
            if (Key is Rijndael)
            {
                switch (Key.KeySize)
                {
                    case 128:
                        encryptionMethod = EncryptedXml.XmlEncAES128Url;
                        break;
                    case 192:
                        encryptionMethod = EncryptedXml.XmlEncAES192Url;
                        break;
                    case 256:
                        encryptionMethod = EncryptedXml.XmlEncAES256Url;
                        break;
                }
            }
            else
            {
                // Throw an exception if the transform is not in the previous categories
                throw new CryptographicException("The specified algorithm is not supported for XML Encryption.");
            }

            edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);

            // Add the encrypted element data to the 
            // EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            ////////////////////////////////////////////////////
            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            ////////////////////////////////////////////////////
            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
        }

        public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg)
        {
            // Check the arguments.  
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (Alg == null)
                throw new ArgumentNullException("Alg");

            // Find the EncryptedData element in the XmlDocument.
            XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement;

            // If the EncryptedData element was not found, throw an exception.
            if (encryptedElement == null)
            {
                throw new XmlException("The EncryptedData element was not found.");
            }

            
            // Create an EncryptedData object and populate it.
            EncryptedData edElement = new EncryptedData();
            edElement.LoadXml(encryptedElement);

            // Create a new EncryptedXml object.
            EncryptedXml exml = new EncryptedXml();
            

            // Decrypt the element using the symmetric key.
            byte[] rgbOutput = exml.DecryptData(edElement, Alg);

            // Replace the encryptedData element with the plaintext XML element.
            exml.ReplaceData(encryptedElement, rgbOutput);

        }

    }


}

這個範例假設,在已編譯程式的相同目錄中,有名為 "test.xml" 的檔案。 它也會假設,"test.xml" 包含 "creditcard" 項目。 您可以將下列 XML 放在名為 test.xml 的檔案中,與這個範例搭配使用。

<root>
    <creditcard>
        <number>19834209</number>
        <expiry>02/02/2002</expiry>
    </creditcard>
</root>

編譯程式碼

安全性

請勿以純文字格式儲存密碼編譯金鑰,也不要將金鑰以純文字形式在電腦之間傳輸。 請改用安全的金鑰容器來儲存密碼編譯金鑰。

當您完成使用密碼編譯金鑰時,請將每個位元組設為零,或呼叫 Managed 加密類別的 Clear 方法,從記憶體清除密碼編譯金鑰。

請參閱

工作

HOW TO:使用對稱金鑰解密 XML 項目

參考

System.Security.Cryptography.Xml

其他資源

XML 加密和數位簽章