Поделиться через


XmlDsigExcC14NTransform Класс

Определение

Представляет эксклюзивное преобразование канонизации XML C14N для цифровой подписи, определенной консорциумом W3C без комментариев.

public ref class XmlDsigExcC14NTransform : System::Security::Cryptography::Xml::Transform
public class XmlDsigExcC14NTransform : System.Security.Cryptography.Xml.Transform
type XmlDsigExcC14NTransform = class
    inherit Transform
Public Class XmlDsigExcC14NTransform
Inherits Transform
Наследование
XmlDsigExcC14NTransform
Производный

Примеры

В следующем примере кода показано, как подписать XML-документ с XmlDsigExcC14NTransform помощью сигнатуры конверта.

//
// This example signs an XML file using an
// envelope signature. It then verifies the
// signed XML.
//
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;

public class SignVerifyEnvelope
{

    public static void Main(String[] args)
    {
        try
        {
            // Generate a signing key.
            RSA Key = RSA.Create();

            // Create an XML file to sign.
            CreateSomeXml("Example.xml");
            Console.WriteLine("New XML file created.");

            // Sign the XML that was just created and save it in a
            // new file.
            SignXmlFile("Example.xml", "SignedExample.xml", Key);
            Console.WriteLine("XML file signed.");

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            bool result = VerifyXmlFile("SignedExample.xml");

            // 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 (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }

    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

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

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Specify a canonicalization method.
        signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

        // Set the InclusiveNamespacesPrefixList property.
        XmlDsigExcC14NTransform canMethod = (XmlDsigExcC14NTransform)signedXml.SignedInfo.CanonicalizationMethodObject;
        canMethod.InclusiveNamespacesPrefixList = "Sign";

        // 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);

        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // 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));

        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
        doc.WriteTo(xmltw);
        xmltw.Close();
    }
    // Verify the signature of an XML file and return the result.
    public static Boolean VerifyXmlFile(String Name)
    {
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // Format using white spaces.
        xmlDocument.PreserveWhitespace = true;

        // Load the passed XML file into the document.
        xmlDocument.Load(Name);

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDocument);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.
        signedXml.LoadXml((XmlElement)nodeList[0]);

        // Check the signature and return the result.
        return signedXml.CheckSignature();
    }

    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
    {
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyXML", "Don't_Sign");

        // Append the node to the document.
        document.AppendChild(node);

        // Create a new XmlNode object.
        XmlNode subnode = document.CreateNode(XmlNodeType.Element, "", "TempElement", "Sign");

        // Add some text to the node.
        subnode.InnerText = "Here is some data to sign.";

        // Append the node to the document.
        document.DocumentElement.AppendChild(subnode);

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
        document.WriteTo(xmltw);
        xmltw.Close();
    }
}
'
' This example signs an XML file using an
' envelope signature. It then verifies the 
' signed XML.
'
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.Xml
Imports System.Text
Imports System.Xml



Module SignVerifyEnvelope


    Sub Main(ByVal args() As String)
        Try
            ' Generate a signing key.
            Dim Key As RSA = RSA.Create()

            ' Create an XML file to sign.
            CreateSomeXml("Example.xml")
            Console.WriteLine("New XML file created.")

            ' Sign the XML that was just created and save it in a 
            ' new file.
            SignXmlFile("Example.xml", "SignedExample.xml", Key)
            Console.WriteLine("XML file signed.")

            ' Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...")
            Dim result As Boolean = VerifyXmlFile("SignedExample.xml")

            ' 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 CryptographicException
            Console.WriteLine(e.Message)
        End Try

    End Sub


    ' Sign an XML file and save the signature in a new file.
    Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA)
        ' Create a new XML document.
        Dim doc As New XmlDocument()

        ' Format the document to ignore white spaces.
        doc.PreserveWhitespace = False

        ' Load the passed XML file using it's name.
        doc.Load(New XmlTextReader(FileName))

        ' Create a SignedXml object.
        Dim signedXml As New SignedXml(doc)

        ' Add the key to the SignedXml document. 
        signedXml.SigningKey = Key

        ' Specify a canonicalization method.
        signedXml.SignedInfo.CanonicalizationMethod = signedXml.XmlDsigExcC14NTransformUrl

        ' Set the InclusiveNamespacesPrefixList property. 
        Dim canMethod As XmlDsigExcC14NTransform = CType(signedXml.SignedInfo.CanonicalizationMethodObject, XmlDsigExcC14NTransform)
        canMethod.InclusiveNamespacesPrefixList = "Sign"

        ' 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)


        ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        Dim keyInfo As New KeyInfo()
        keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA)))
        signedXml.KeyInfo = keyInfo

        ' 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))


        If TypeOf doc.FirstChild Is XmlDeclaration Then
            doc.RemoveChild(doc.FirstChild)
        End If

        ' Save the signed XML document to a file specified
        ' using the passed string.
        Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False))
        doc.WriteTo(xmltw)
        xmltw.Close()

    End Sub

    ' Verify the signature of an XML file and return the result.
    Function VerifyXmlFile(ByVal Name As String) As [Boolean]
        ' Create a new XML document.
        Dim xmlDocument As New XmlDocument()

        ' Format using white spaces.
        xmlDocument.PreserveWhitespace = True

        ' Load the passed XML file into the document. 
        xmlDocument.Load(Name)

        ' Create a new SignedXml object and pass it
        ' the XML document class.
        Dim signedXml As New SignedXml(xmlDocument)

        ' Find the "Signature" node and create a new
        ' XmlNodeList object.
        Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature")

        ' Load the signature node.
        signedXml.LoadXml(CType(nodeList(0), XmlElement))

        ' Check the signature and return the result.
        Return signedXml.CheckSignature()

    End Function


    ' Create example data to sign.
    Sub CreateSomeXml(ByVal FileName As String)
        ' Create a new XmlDocument object.
        Dim document As New XmlDocument()

        ' Create a new XmlNode object.
        Dim node As XmlNode = document.CreateNode(XmlNodeType.Element, "", "MyXML", "Don't_Sign")

        ' Append the node to the document.
        document.AppendChild(node)

        ' Create a new XmlNode object.
        Dim subnode As XmlNode = document.CreateNode(XmlNodeType.Element, "", "TempElement", "Sign")

        ' Add some text to the node.
        subnode.InnerText = "Here is some data to sign."

        ' Append the node to the document.
        document.DocumentElement.AppendChild(subnode)

        ' Save the XML document to the file name specified.
        Dim xmltw As New XmlTextWriter(FileName, New UTF8Encoding(False))
        document.WriteTo(xmltw)
        xmltw.Close()

    End Sub
End Module

Комментарии

Класс XmlDsigExcC14NTransform представляет эксклюзивное преобразование канонизации XML C14N без комментариев. Этот класс аналогичен XmlDsigC14NTransform классу, который позволяет подписыванию создавать дайджест с помощью канонической формы XML-документа. XmlDsigExcC14NTransform Однако класс исключает контекст предка из канонизованного поддокумента.

XmlDsigC14NTransform Используйте класс, когда необходимо канонизировать поддокумент XML, чтобы он не зависит от его контекста XML. Например, такие приложения, как веб-службы, использующие подписанный XML в сложных протоколах связи, часто должны канонизировать XML таким образом. Такие приложения часто включают XML в различные динамически созданные элементы, что может существенно изменить документ и привести к сбою проверки подписи XML. Класс XmlDsigExcC14NTransform решает эту проблему путем исключения такого контекста предка из канонического поддокумента.

Как правило, вы не создаете новый экземпляр класса преобразования канонизации. Чтобы указать преобразование канонизации, передайте универсальный код ресурса (URI), описывающий преобразование в CanonicalizationMethod свойство, которое доступно из SignedInfo свойства. Чтобы получить ссылку на преобразование канонизации, используйте CanonicalizationMethodObject свойство, доступное SignedInfo из свойства.

Для создания нового экземпляра класса преобразования канонизации требуется только в том случае, если требуется вручную хэшировать XML-документ или использовать собственный алгоритм канонизации.

Универсальный код ресурса (URI), описывающий XmlDsigExcC14NWithCommentsTransform класс, определяется полем XmlDsigExcC14NWithCommentsTransformUrl .

Универсальный код ресурса (URI), описывающий XmlDsigExcC14NTransform класс, определяется полем XmlDsigExcC14NTransformUrl .

Дополнительные сведения об эксклюзивном преобразовании C14N см. в спецификации W3C XMLDSIG. Алгоритм канонизации определен в спецификации W3C Canonical XML.

Конструкторы

Имя Описание
XmlDsigExcC14NTransform()

Инициализирует новый экземпляр класса XmlDsigExcC14NTransform.

XmlDsigExcC14NTransform(Boolean, String)

Инициализирует новый экземпляр XmlDsigExcC14NTransform класса, указывающий, следует ли включать примечания и указывать список префиксов пространства имен.

XmlDsigExcC14NTransform(Boolean)

Инициализирует новый экземпляр XmlDsigExcC14NTransform класса, указывающий значение, определяющее, следует ли включать примечания.

XmlDsigExcC14NTransform(String)

Инициализирует новый экземпляр XmlDsigExcC14NTransform класса, указывающий список префиксов пространства имен для канонизации с помощью стандартного алгоритма канонизации.

Свойства

Имя Описание
Algorithm

Возвращает или задает универсальный идентификатор ресурса (URI), определяющий алгоритм, выполняемый текущим преобразованием.

(Унаследовано от Transform)
Context

Возвращает или задает XmlElement объект, представляющий контекст документа, в котором выполняется текущий Transform объект.

(Унаследовано от Transform)
InclusiveNamespacesPrefixList

Возвращает или задает строку, содержащую префиксы пространства имен для канонизации с помощью стандартного алгоритма канонизации.

InputTypes

Возвращает массив типов, которые являются допустимыми входными данными для LoadInput(Object) метода текущего XmlDsigExcC14NTransform объекта.

OutputTypes

Возвращает массив типов, которые могут быть выходными данными из GetOutput() методов текущего XmlDsigExcC14NTransform объекта.

PropagatedNamespaces

Получает или задает Hashtable объект, содержащий пространства имен, распространяемые в сигнатуру.

(Унаследовано от Transform)
Resolver

Задает текущий XmlResolver объект.

(Унаследовано от Transform)

Методы

Имя Описание
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetDigestedOutput(HashAlgorithm)

Возвращает дайджест, связанный XmlDsigExcC14NTransform с объектом.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetInnerXml()

Возвращает XML-представление параметров XmlDsigExcC14NTransform объекта, который подходит для включения в качестве подэлементов элемента XMLDSIG <Transform> .

GetOutput()

Возвращает выходные данные текущего XmlDsigExcC14NTransform объекта.

GetOutput(Type)

Возвращает выходные данные текущего XmlDsigExcC14NTransform объекта в качестве объекта указанного типа.

GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
GetXml()

Возвращает XML-представление текущего Transform объекта.

(Унаследовано от Transform)
LoadInnerXml(XmlNodeList)

Анализирует указанный XmlNodeList объект в виде содержимого <Transform> элемента, зависяющего от преобразования, и настраивает внутреннее состояние текущего XmlDsigExcC14NTransform объекта в соответствии с элементом <Transform> .

LoadInput(Object)

При переопределении в производном классе загружает указанные входные данные в текущий XmlDsigExcC14NTransform объект.

MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к