다음을 통해 공유


방법: 디지털 서명으로 XML 문서 서명

업데이트: 2007년 11월

System.Security.Cryptography.Xml 네임스페이스의 클래스를 사용하여 XML 문서 또는 XML 문서의 일부를 디지털 서명으로 서명할 수 있습니다. XML 디지털 서명(XMLDSIG)을 사용하면 서명 후 데이터 변경 여부를 확인할 수 있습니다. XMLDSIG 표준에 대한 자세한 내용은 http://www.w3.org/TR/xmldsig-core/에서 W3C(World Wide Web 컨소시엄) 사양을 참조하십시오.

이 절차의 코드 예제에서는 XML 전체 문서를 디지털 서명하고 서명을 <Signature> 요소의 문서에 추가하는 방법에 대해 설명합니다. 이 예제에서는 RSA 서명 키를 만들고 보안 키 컨테이너에 추가한 다음 이 키를 사용하여 XML 문서를 디지털 서명합니다. 그런 다음 이 키를 검색하여 XML 디지털 서명을 확인하거나 다른 XML 문서를 서명할 수 있습니다.

이 절차를 통해 생성된 XML 디지털 서명을 확인하는 방법에 대한 자세한 내용은 방법: 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 클래스의 생성자로 전달할 때 키 컨테이너로 자동 저장됩니다. 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(Doc)
    
    SignedXml signedXml = new SignedXml(Doc);
    
  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. Reference 개체에 XmlDsigEnvelopedSignatureTransform 개체를 추가합니다. 검증 도구는 변환을 통해 서명자가 사용한 것과 동일한 방식으로 XML 데이터를 나타낼 수 있습니다. XML 데이터는 다른 방식으로 나타낼 수 있으므로 이 단계는 검증에 중요한 역할을 합니다.

    Dim env As New XmlDsigEnvelopedSignatureTransform()
    reference.AddTransform(env)
    
    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);
    
  8. SignedXml 개체에 Reference 개체를 추가합니다.

    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 개체에 추가합니다.

    Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, True))
    
    Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
    
  12. 문서를 저장합니다.

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

예제

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 Doc As XmlDocument, ByVal Key As RSA)
        ' 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 SignedXml object.
        Dim signedXml As New SignedXml(Doc)
        ' 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.
        Doc.DocumentElement.AppendChild(Doc.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 Doc, RSA Key)
    {
        // Check arguments.
        if (Doc == null)
            throw new ArgumentException("Doc");
        if (Key == null)
            throw new ArgumentException("Key");

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(Doc);

        // 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.
        Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));

    }
}

이 예제에서는 컴파일된 프로그램과 같은 디렉터리에 "test.xml" 파일이 있다고 가정합니다. 다음 XML을 test.xml 파일에 추가한 다음 이 예제에서 사용할 수 있습니다.

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

코드 컴파일

보안

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

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

참고 항목

작업

방법: XML 문서의 디지털 서명 확인

참조

System.Security.Cryptography.Xml

기타 리소스

XML 암호화 및 디지털 서명