방법: XML 문서의 디지털 서명 확인
업데이트: 2007년 11월
System.Security.Cryptography.Xml 네임스페이스의 클래스를 사용하여 디지털 서명으로 서명된 XML 데이터를 확인할 수 있습니다. XMLDSIG(XML 디지털 서명)를 사용하면 서명 후 데이터 변경 여부를 확인할 수 있습니다. XMLDSIG 표준에 대한 자세한 내용은 http://www.w3.org/TR/xmldsig-core/에서 W3C(World Wide Web 컨소시엄) 사양을 참조하십시오.
이 절차의 코드 예제에서는 <Signature> 요소에 포함된 XML 디지털 서명을 확인하는 방법에 대해 설명합니다. 이 예제에서는 키 컨테이너에서 RSA 공개 키를 검색한 다음 이 키를 사용하여 서명을 확인합니다.
이 기술을 사용하여 확인 가능한 디지털 서명을 만드는 방법에 대한 자세한 내용은 방법: 디지털 서명으로 XML 문서 서명을 참조하십시오.
XML 문서의 디지털 서명을 확인하려면
문서를 확인하려면 서명에 사용했던 것과 동일한 비대칭 키를 사용해야 합니다. CspParameters 개체를 만들고 서명에 사용되었던 키 컨테이너의 이름을 지정합니다.
Dim cspParams As New CspParameters() cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"
CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
RSACryptoServiceProvider 클래스를 사용하여 공개 키를 검색합니다. 이 키는 CspParameters 개체를 RSACryptoServiceProvider 클래스의 생성자로 전달할 때 이름으로 키 컨테이너에서 자동 로드됩니다.
Dim rsaKey As New RSACryptoServiceProvider(cspParams)
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
디스크에서 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");
새 SignedXml 개체를 만들고 XmlDocument 개체를 여기에 전달합니다.
Dim signedXml As New SignedXml(Doc)
SignedXml signedXml = new SignedXml(Doc);
<signature> 요소를 찾고 새 XmlNodeList 개체를 만듭니다.
Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
첫 번째 <signature> 요소의 XML을 SignedXml 개체로 로드합니다.
signedXml.LoadXml(CType(nodeList(0), XmlElement))
signedXml.LoadXml((XmlElement)nodeList[0]);
CheckSignature 메서드와 RSA 공개 키를 사용하여 서명을 확인합니다. 이 메서드는 성공 또는 실패 여부를 나타내는 부울 값을 반환합니다.
Return signedXml.CheckSignature(Key)
return signedXml.CheckSignature(Key);
예제
Imports System
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Xml
Module VerifyXML
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")
' Verify the signature of the signed XML.
Console.WriteLine("Verifying signature...")
Dim result As Boolean = VerifyXml(xmlDoc, rsaKey)
' Display the results of the signature verification to
' the console.
If result Then
Console.WriteLine("The XML signature is valid.")
Else
Console.WriteLine("The XML signature is not valid.")
End If
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
' Verify the signature of an XML file against an asymmetric
' algorithm and return the result.
Function VerifyXml(ByVal Doc As XmlDocument, ByVal Key As RSA) As [Boolean]
' Check arguments.
If Doc Is Nothing Then
Throw New ArgumentException("Doc")
End If
If Key Is Nothing Then
Throw New ArgumentException("Key")
End If
' Create a new SignedXml object and pass it
' the XML document class.
Dim signedXml As New SignedXml(Doc)
' Find the "Signature" node and create a new
' XmlNodeList object.
Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
' Throw an exception if no signature was found.
If nodeList.Count <= 0 Then
Throw New CryptographicException("Verification failed: No Signature was found in the document.")
End If
' This example only supports one signature for
' the entire XML document. Throw an exception
' if more than one signature was found.
If nodeList.Count >= 2 Then
Throw New CryptographicException("Verification failed: More that one signature was found for the document.")
End If
' Load the first <signature> node.
signedXml.LoadXml(CType(nodeList(0), XmlElement))
' Check the signature and return the result.
Return signedXml.CheckSignature(Key)
End Function
End Module
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;
public class VerifyXML
{
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");
// Verify the signature of the signed XML.
Console.WriteLine("Verifying signature...");
bool result = VerifyXml(xmlDoc, rsaKey);
// Display the results of the signature verification to
// the console.
if (result)
{
Console.WriteLine("The XML signature is valid.");
}
else
{
Console.WriteLine("The XML signature is not valid.");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
// Verify the signature of an XML file against an asymmetric
// algorithm and return the result.
public static Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
// Check arguments.
if (Doc == null)
throw new ArgumentException("Doc");
if (Key == null)
throw new ArgumentException("Key");
// Create a new SignedXml object and pass it
// the XML document class.
SignedXml signedXml = new SignedXml(Doc);
// Find the "Signature" node and create a new
// XmlNodeList object.
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
// Throw an exception if no signature was found.
if (nodeList.Count <= 0)
{
throw new CryptographicException("Verification failed: No Signature was found in the document.");
}
// This example only supports one signature for
// the entire XML document. Throw an exception
// if more than one signature was found.
if (nodeList.Count >= 2)
{
throw new CryptographicException("Verification failed: More that one signature was found for the document.");
}
// Load the first <signature> node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(Key);
}
}
이 예제에서는 컴파일된 프로그램과 같은 디렉터리에 "test.xml" 파일이 있다고 가정합니다. "test.xml" 파일은 방법: 디지털 서명으로 XML 문서 서명에서 설명한 기술을 사용하여 서명되어야 합니다.
코드 컴파일
이 예제를 컴파일하려면 System.Security.dll에 대한 참조를 포함해야 합니다.
System.Xml, System.Security.Cryptography 및 System.Security.Cryptography.Xml 네임스페이스를 포함합니다.
보안
비대칭 키 쌍의 개인 키를 일반 텍스트로 저장하거나 전송하지 마십시오. 대칭 및 비대칭 암호화 키에 대한 자세한 내용은 암호화 및 해독용 키 생성을 참조하십시오.
개인 키를 소스 코드에 직접 포함시키지 마십시오. 포함된 키는 어셈블리에서 MSIL 디스어셈블러(Ildasm.exe)를 사용하거나 메모장과 같은 텍스트 편집기로 어셈블리를 열어서 쉽게 읽을 수 있습니다.
참고 항목
작업
참조
System.Security.Cryptography.Xml