Share via


방법: 비대칭 키를 사용하여 XML 요소 해독

업데이트: 2010년 7월

System.Security.Cryptography.Xml 네임스페이스의 클래스를 사용하여 XML 문서 내의 요소를 암호화하고 해독할 수 있습니다. XML 암호화는 데이터가 쉽게 읽힐 염려 없이 암호화된 XML 데이터를 교환하거나 저장할 수 있는 표준 방식입니다. XML 암호화 표준에 대한 자세한 내용은 W3C(World Wide Web Consortium) 권장 사항 XML Signature Syntax and Processing을 참조하십시오.

이 절차의 예제에서는 방법: 비대칭 키를 사용하여 XML 요소 암호화에서 설명한 메서드를 사용하여 암호화된 XML 요소를 해독합니다. <EncryptedData> 요소를 찾아 해독한 다음 이 요소를 원래의 일반 텍스트 XML 요소로 바꿉니다.

이 예제에서는 두 가지 키를 사용하여 XML 요소를 해독합니다. 이전에 생성된 RSA 개인 키를 키 컨테이너에서 검색한 다음 이 RSA 키를 사용하여 <EncryptedData> 요소의 <EncryptedKey> 요소에 저장된 세션 키를 해독합니다. 그런 다음 세션 키를 사용하여 XML 요소를 해독합니다.

이 예제는 여러 응용 프로그램에서 암호화된 데이터를 공유해야 하거나 단일 응용 프로그램에서 실행 시점 사이에 암호화된 데이터를 저장해야 하는 경우에 적절합니다.

비대칭 키로 XML 요소를 해독하려면

  1. CspParameters 개체를 만들고 키 컨테이너의 이름을 지정합니다.

    Dim cspParams As New CspParameters()
    cspParams.KeyContainerName = "XML_ENC_RSA_KEY"
    
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "XML_ENC_RSA_KEY";
    
  2. RSACryptoServiceProvider 개체를 사용하여 컨테이너에서 이전에 생성된 비대칭 키를 검색합니다. 이 키는 CspParameters 개체를 RSACryptoServiceProvider 생성자로 전달할 때 키 컨테이너에서 자동 검색됩니다.

    Dim rsaKey As New RSACryptoServiceProvider(cspParams)
    
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
    
  3. EncryptedXml 개체를 만들어 문서를 해독합니다.

    ' Create a new EncryptedXml object.
    Dim exml As New EncryptedXml(Doc)
    
            // Create a new EncryptedXml object.
            EncryptedXml exml = new EncryptedXml(Doc);
    
  4. 해독할 문서 내의 요소와 RSA 키를 연결하기 위해 키/이름 매핑을 추가합니다. 문서를 암호화할 때 사용한 키와 동일한 이름을 사용해야 합니다. 이 이름은 1단계에서 지정된 키 컨테이너에서 키를 식별하는 데 사용하는 이름과는 구분됩니다.

    exml.AddKeyNameMapping(KeyName, Alg)
    
            exml.AddKeyNameMapping(KeyName, Alg);
    
  5. DecryptDocument 메서드를 호출하여 <EncryptedData> 요소를 해독합니다. 이 메서드에서는 RSA 키를 사용하여 세션 키를 해독하고, 세션 키를 자동으로 사용하여 XML 요소를 해독합니다. 또한 <EncryptedData> 요소를 원래의 일반 텍스트로 자동 대체합니다.

    exml.DecryptDocument()
    
            exml.DecryptDocument();
    
  6. XML 문서를 저장합니다.

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

예제

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



Module Program

    Sub Main(ByVal args() As String)

        ' Create an XmlDocument object.
        Dim xmlDoc As New XmlDocument()

        ' Load an XML file into the XmlDocument object.
        Try
            xmlDoc.PreserveWhitespace = True
            xmlDoc.Load("test.xml")
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
        Dim cspParams As New CspParameters()
        cspParams.KeyContainerName = "XML_ENC_RSA_KEY"
        ' Get the RSA key from the key container.  This key will decrypt 
        ' a symmetric key that was imbedded in the XML document. 
        Dim rsaKey As New RSACryptoServiceProvider(cspParams)
        Try

            ' Decrypt the elements.
            Decrypt(xmlDoc, rsaKey, "rsaKey")

            ' Save the XML document.
            xmlDoc.Save("test.xml")
            ' Display the encrypted XML to the console.
            Console.WriteLine()
            Console.WriteLine("Decrypted XML:")
            Console.WriteLine()
            Console.WriteLine(xmlDoc.OuterXml)
        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally
            ' Clear the RSA key.
            rsaKey.Clear()
        End Try


        Console.ReadLine()

    End Sub



    Sub Decrypt(ByVal Doc As XmlDocument, ByVal Alg As RSA, ByVal KeyName As String)
        ' 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
        If KeyName Is Nothing Then
            Throw New ArgumentNullException("KeyName")
        End If 
        ' Create a new EncryptedXml object.
        Dim exml As New EncryptedXml(Doc)
        ' Add a key-name mapping.
        ' This method can only decrypt documents
        ' that present the specified key name.
        exml.AddKeyNameMapping(KeyName, Alg)
        ' Decrypt the element.
        exml.DecryptDocument()
    End Sub
End Module


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

class Program
{
    static void Main(string[] args)
    {

        // Create an XmlDocument object.
        XmlDocument xmlDoc = new XmlDocument();

        // Load an XML file into the XmlDocument object.
        try
        {
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load("test.xml");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        CspParameters cspParams = new CspParameters();
        cspParams.KeyContainerName = "XML_ENC_RSA_KEY";

        // Get the RSA key from the key container.  This key will decrypt
        // a symmetric key that was imbedded in the XML document.
        RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

        try
        {

            // Decrypt the elements.
            Decrypt(xmlDoc, rsaKey, "rsaKey");

            // Save the XML document.
            xmlDoc.Save("test.xml");

            // Display the encrypted XML to the console.
            Console.WriteLine();
            Console.WriteLine("Decrypted XML:");
            Console.WriteLine();
            Console.WriteLine(xmlDoc.OuterXml);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Clear the RSA key.
            rsaKey.Clear();
        }


        Console.ReadLine();


    }

    public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName)
    {
        // Check the arguments.
        if (Doc == null)
            throw new ArgumentNullException("Doc");
        if (Alg == null)
            throw new ArgumentNullException("Alg");
        if (KeyName == null)
            throw new ArgumentNullException("KeyName");
        // Create a new EncryptedXml object.
        EncryptedXml exml = new EncryptedXml(Doc);

        // Add a key-name mapping.
        // This method can only decrypt documents
        // that present the specified key name.
        exml.AddKeyNameMapping(KeyName, Alg);

        // Decrypt the element.
        exml.DecryptDocument();

    }

}

이 예제에서는 컴파일된 프로그램과 같은 디렉터리에 test.xml 파일이 있다고 가정합니다. 또한 test.xml에 방법: 비대칭 키를 사용하여 XML 요소 암호화에서 설명한 기술을 사용하여 암호화된 XML 요소가 들어 있다고 가정합니다.

코드 컴파일

보안

대칭 암호화 키를 일반 텍스트로 저장하거나 시스템 간의 키를 일반 텍스트로 전송하지 마십시오. 또한 비대칭 키 쌍의 개인 키를 일반 텍스트로 저장하거나 전송하지 마십시오. 대칭 및 비대칭 암호화 키에 대한 자세한 내용은 암호화 및 해독용 키 생성을 참조하십시오.

키를 소스 코드에 직접 포함시키지 마십시오. 포함된 키는 어셈블리에서 Ildasm.exe(MSIL 디스어셈블러)를 사용하거나 메모장과 같은 텍스트 편집기로 어셈블리를 열어서 쉽게 읽을 수 있습니다.

암호화 키 사용을 마쳤으면 각 바이트를 0으로 설정하거나 관리되는 암호화 클래스의 Clear 메서드를 호출하여 메모리에서 암호화 키를 지웁니다. 암호화 키는 디버거에 의해 메모리에서 읽히거나 메모리 위치가 디스크로 페이징되는 경우 하드 드라이브에서 읽힐 수 있습니다.

참고 항목

작업

방법: 비대칭 키를 사용하여 XML 요소 암호화

참조

System.Security.Cryptography.Xml

기타 리소스

XML 암호화 및 디지털 서명

변경 기록

날짜

변경 내용

이유

2010년 7월

순서가 잘못된 예제가 수정되었습니다.

고객 의견