System.Security.Cryptography.Xml 네임스페이스의 클래스를 사용하여 XML 문서 내의 요소를 암호화 및 암호 해독할 수 있습니다. XML 암호화는 데이터가 쉽게 읽혀질 염려 없이 암호화된 XML 데이터를 교환하거나 저장하는 표준 방법입니다. XML 암호화 표준에 대한 자세한 내용은 W3C(World Wide Web 컨소시엄) 권장 사항 XML 서명 구문 및 처리를 참조하세요.
참고 항목
이 문서의 코드는 Windows에 적용됩니다.
이 절차의 예에서는 방법: 비대칭 키로 XML 요소 암호화에 설명된 메서드를 사용하여 암호화된 XML 요소를 암호 해독합니다. <EncryptedData> 요소를 찾아 암호 해독한 다음 이 요소를 원래의 일반 텍스트 XML 요소로 바꿉니다.
이 예제에서는 두 키를 사용하여 XML 요소를 암호 해독합니다. 이전에 생성된 RSA 프라이빗 키를 키 컨테이너에서 검색한 다음 RSA 키를 사용하여 <EncryptedData> 요소의 <EncryptedKey> 요소에 저장된 세션 키를 해독합니다. 그런 다음 예제에서는 세션 키를 사용하여 XML 요소를 암호 해독합니다.
이 예제는 여러 애플리케이션이 암호화된 데이터를 공유해야 하거나 애플리케이션이 실행되는 시간 사이에 암호화된 데이터를 저장해야 경우에 적합합니다.
비대칭 키를 사용하여 XML 요소를 암호 해독하려면
CspParameters 개체를 만들고 키 컨테이너의 이름을 지정합니다.
CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_ENC_RSA_KEY";Dim cspParams As New CspParameters() cspParams.KeyContainerName = "XML_ENC_RSA_KEY"RSACryptoServiceProvider 개체를 사용하여 컨테이너에서 이전에 생성된 비대칭 키를 검색합니다. RSACryptoServiceProvider 생성자에 CspParameters 개체를 전달하면 키가 자동으로 키 컨테이너에서 검색됩니다.
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);Dim rsaKey As New RSACryptoServiceProvider(cspParams)새 EncryptedXml 개체를 만들어 문서를 암호 해독합니다.
// Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(Doc);' Create a new EncryptedXml object. Dim exml As New EncryptedXml(Doc)암호 해독해야 하는 문서 내의 요소와 RSA 키를 연결하는 키/이름 매핑을 추가합니다. 문서를 암호화할 때 사용한 것과 동일한 키 이름을 사용해야 합니다. 이 이름은 1단계에서 지정한, 키 컨테이너에서 키를 식별하는 데 사용되는 이름과 별개입니다.
exml.AddKeyNameMapping(KeyName, Alg);exml.AddKeyNameMapping(KeyName, Alg)DecryptDocument 메서드를 호출하여 <
EncryptedData> 요소를 해독합니다. 이 메서드는 RSA 키를 사용하여 세션 키를 암호 해독하고 자동으로 세션 키를 사용하여 XML 요소를 암호 해독합니다. 또한 <EncryptedData> 요소를 원래 일반 텍스트로 자동으로 바꿉니다.exml.DecryptDocument();exml.DecryptDocument()XML 문서를 저장합니다.
xmlDoc.Save("test.xml");xmlDoc.Save("test.xml")
예시
이 예제에서는 test.xml이라는 파일이 컴파일된 프로그램과 동일한 디렉터리에 있다고 가정합니다. 또한 방법: 비대칭 키로 XML 요소 암호화에 설명된 기술을 사용하여 암호화된 XML 요소가 test.xml에 들어 있다고 가정합니다.
using System;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Runtime.Versioning;
[SupportedOSPlatform("windows")]
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();
}
}
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.
ArgumentNullException.ThrowIfNull(Doc)
ArgumentNullException.ThrowIfNull(Alg)
ArgumentNullException.ThrowIfNull(KeyName)
' 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
코드 컴파일
.NET Framework를 대상으로 하는 프로젝트에서
System.Security.dll에 대한 참조를 포함합니다..NET Core 또는 .NET 5를 대상으로 하는 프로젝트에서 NuGet 패키지 System.Security.Cryptography.Xml을 설치합니다.
System.Xml, System.Security.Cryptography 및 System.Security.Cryptography.Xml 네임스페이스를 포함합니다.
.NET 보안
대칭 암호화 키를 일반 텍스트로 저장하거나 컴퓨터 간에 일반 텍스트로 대칭 키를 전송하지 마세요. 또한 비대칭 키 쌍의 프라이빗 키를 일반 텍스트로 저장하거나 전송하지 마세요. 대칭 및 비대칭 암호화 키에 대한 자세한 내용은 암호화 및 암호 해독용 키 생성을 참조하세요.
소스 코드에 직접 키를 포함하지 마세요. Ildasm.exe(IL 디스어셈블러)를 사용하거나 메모장과 같은 텍스트 편집기에서 어셈블리를 열어 어셈블리에서 포함된 키를 쉽게 읽을 수 있습니다.
암호화 키를 사용하여 작업이 완료되면 각 바이트를 0으로 설정하거나 관리되는 암호화 클래스의 Clear 메서드를 호출하여 메모리에서 지웁니다. 디버거가 메모리에서 암호화 키를 읽거나 메모리 위치가 디스크에 페이징된 경우 하드 드라이브에서 읽을 수 있는 경우도 있습니다.
참고 항목
.NET