XmlDsigC14NWithCommentsTransform 类   
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示由万维网联合会 (W3C) 定义的数字签名的 C14N XML 标准化转换(带注释)。
public ref class XmlDsigC14NWithCommentsTransform : System::Security::Cryptography::Xml::XmlDsigC14NTransformpublic class XmlDsigC14NWithCommentsTransform : System.Security.Cryptography.Xml.XmlDsigC14NTransformtype XmlDsigC14NWithCommentsTransform = class
    inherit XmlDsigC14NTransformPublic Class XmlDsigC14NWithCommentsTransform
Inherits XmlDsigC14NTransform- 继承
示例
本部分包含两个代码示例。 第一个示例演示如何使用分离签名对 XML 文件进行签名。 此示例在 XML 文件中创建 的 www.microsoft.com 签名,然后验证该文件。 第二个示例演示如何使用信封签名对 XML 文件进行签名。  此示例创建 XML 文件的签名,然后将该签名保存在新的 XML 文件中。
示例 #1
//
// This example signs a file specified by a URI 
// using a detached signature. It then verifies  
// the signed XML.
//
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;
class XMLDSIGDetached
{
    
    [STAThread]
    static void Main(string[] args)
    {
        // The URI to sign.
        string resourceToSign = "http://www.microsoft.com";
        
        // The name of the file to which to save the XML signature.
        string XmlFileName = "xmldsig.xml";
        try
        {
            // Generate a signing key.
            RSA Key = RSA.Create();
            Console.WriteLine("Signing: {0}", resourceToSign);
            // Sign the detached resourceand save the signature in an XML file.
            SignDetachedResource(resourceToSign, XmlFileName, Key);
            Console.WriteLine("XML signature was successfully computed and saved to {0}.", XmlFileName);
            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            //Verify the XML signature in the XML file.
            bool result = VerifyDetachedSignature(XmlFileName);
            // 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 SignDetachedResource(string URIString, string XmlSigFileName, RSA Key)
    {
        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml();
        // Assign the key to the SignedXml object.
        signedXml.SigningKey = Key;
        // Create a reference to be signed.
        Reference reference = new Reference();
        // Add the passed URI to the reference object.
        reference.Uri = URIString;
        
        // 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();
        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false));
        xmlDigitalSignature.WriteTo(xmltw);
        xmltw.Close();
    }
    // Verify the signature of an XML file and return the result.
    public static Boolean VerifyDetachedSignature(string XmlSigFileName)
    {	
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();
        // Load the passed XML file into the document.
        xmlDocument.Load(XmlSigFileName);
    
        // Create a new SignedXMl object.
        SignedXml signedXml = new SignedXml();
        // 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();
    }
}
' This example signs a file specified by a URI 
' using a detached signature. It then verifies  
' the signed XML.
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Text
Imports System.Xml
Class XMLDSIGDetached
   
   <STAThread()>  _
   Overloads Shared Sub Main(args() As String)
      ' The URI to sign.
      Dim resourceToSign As String = "http://www.microsoft.com"
      
      ' The name of the file to which to save the XML signature.
      Dim XmlFileName As String = "xmldsig.xml"
      
      Try
         
         ' Generate a signing key.
         Dim Key As RSA = RSA.Create()
         
         Console.WriteLine("Signing: {0}", resourceToSign)
         
         ' Sign the detached resourceand save the signature in an XML file.
         SignDetachedResource(resourceToSign, XmlFileName, Key)
         
         Console.WriteLine("XML signature was successfully computed and saved to {0}.", XmlFileName)
         
         ' Verify the signature of the signed XML.
         Console.WriteLine("Verifying signature...")
         
         'Verify the XML signature in the XML file.
         Dim result As Boolean = VerifyDetachedSignature(XmlFileName)
         
         ' 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.
   Public Shared Sub SignDetachedResource(URIString As String, XmlSigFileName As String, Key As RSA)
      ' Create a SignedXml object.
      Dim signedXml As New SignedXml()
      
      ' Assign the key to the SignedXml object.
      signedXml.SigningKey = Key
      
      ' Create a reference to be signed.
      Dim reference As New Reference()
      
      ' Add the passed URI to the reference object.
      reference.Uri = URIString
      
      ' 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()
      
      ' Save the signed XML document to a file specified
      ' using the passed string.
      Dim xmltw As New XmlTextWriter(XmlSigFileName, New UTF8Encoding(False))
      xmlDigitalSignature.WriteTo(xmltw)
      xmltw.Close()
   End Sub 
   
   ' Verify the signature of an XML file and return the result.
   Public Shared Function VerifyDetachedSignature(XmlSigFileName As String) As [Boolean]
      ' Create a new XML document.
      Dim xmlDocument As New XmlDocument()
      
      ' Load the passed XML file into the document.
      xmlDocument.Load(XmlSigFileName)
      
      ' Create a new SignedXMl object.
      Dim signedXml As New SignedXml()
      
      ' 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
End Class
示例 #2
// 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.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;
        // 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, "", "MyElement", "samples");
        
        // Add some text to the node.
        node.InnerText = "Example text to be signed.";
        // Append the node to the document.
        document.AppendChild(node);
        // 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.Xml
Imports System.Text
Imports System.Xml
Public Class SignVerifyEnvelope
   Overloads Public Shared Sub Main(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.
   Public Shared Sub SignXmlFile(FileName As String, SignedFileName As String, 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
      
      ' 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.
   Public Shared Function VerifyXmlFile(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.
   Public Shared Sub CreateSomeXml(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, "", "MyElement", "samples")
      
      ' Add some text to the node.
      node.InnerText = "Example text to be signed."
      
      ' Append the node to the document.
      document.AppendChild(node)
      
      ' 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 Class
注解
类 XmlDsigC14NWithCommentsTransform 表示 C14N XML 规范化转换,该转换描述 XML 文档的规范形式。 此转换允许签名者使用 XML 文档的规范形式创建摘要。 然后,收件人可以使用 XML 文档的相同规范形式来验证数字签名,并执行相同的转换。
XmlDsigC14NWithCommentsTransform需要对包含注释的 XML 文档进行签名时,请使用 类。
请注意,不能直接创建规范化转换类的新实例。 若要指定规范化转换,请将描述转换的统一资源标识符 (URI) 传递给 CanonicalizationMethod 属性,该属性可从 SignedInfo 属性访问。 若要获取对规范化转换的引用,请使用 CanonicalizationMethodObject 可从 属性访问 SignedInfo 的 属性。
描述 类的 XmlDsigExcC14NWithCommentsTransform URI 由 XmlDsigExcC14NWithCommentsTransformUrl 字段定义。
描述类的 XmlDsigC14NWithCommentsTransform URI 由 XmlDsigC14NWithCommentsTransformUrl 字段和 XmlDsigCanonicalizationWithCommentsUrl 字段定义。
有关带有注释转换的 C14N 的详细信息,请参阅 W3C XMLDSIG 规范的第 6.5 和 6.6.1 部分。 规范化算法在 W3C 规范 XML 规范中定义。
构造函数
| XmlDsigC14NWithCommentsTransform() | 初始化 XmlDsigC14NWithCommentsTransform 类的新实例。 | 
属性
| Algorithm | 获取或设置用于标识当前转换所执行的算法的统一资源标识符 (URI)。(继承自 Transform) | 
| Context | 获取或设置一个 XmlElement 对象,该对象表示当前 Transform 对象运行的文档上下文。(继承自 Transform) | 
| InputTypes | 获取一个类型数组,这些类型是当前 XmlDsigC14NTransform 对象的 LoadInput(Object) 方法的有效输入。(继承自 XmlDsigC14NTransform) | 
| OutputTypes | 获取一个类型数组,这些类型是当前 XmlDsigC14NTransform 对象的 GetOutput() 方法的可能输出。(继承自 XmlDsigC14NTransform) | 
| PropagatedNamespaces | 获取或设置一个 Hashtable 对象,该对象包含传播到签名中的命名空间。(继承自 Transform) | 
| Resolver | 设置当前的 XmlResolver 对象。(继承自 Transform) | 
方法
| Equals(Object) | 确定指定对象是否等于当前对象。(继承自 Object) | 
| GetDigestedOutput(HashAlgorithm) | 返回与 XmlDsigC14NTransform 对象关联的摘要。(继承自 XmlDsigC14NTransform) | 
| GetHashCode() | 作为默认哈希函数。(继承自 Object) | 
| GetInnerXml() | 返回 XmlDsigC14NTransform 对象的参数的 XML 表示形式,适合以 XMLDSIG  | 
| GetOutput() | 返回当前 XmlDsigC14NTransform 对象的输出。(继承自 XmlDsigC14NTransform) | 
| GetOutput(Type) | 返回 Stream 类型的当前 XmlDsigC14NTransform 对象的输出。(继承自 XmlDsigC14NTransform) | 
| GetType() | 获取当前实例的 Type。(继承自 Object) | 
| GetXml() | 返回当前 Transform 对象的 XML 表示形式。(继承自 Transform) | 
| LoadInnerXml(XmlNodeList) | 将指定的 XmlNodeList 对象分析为  | 
| LoadInput(Object) | 将指定的输入加载到当前 XmlDsigC14NTransform 对象中。(继承自 XmlDsigC14NTransform) | 
| MemberwiseClone() | 创建当前 Object 的浅表副本。(继承自 Object) | 
| ToString() | 返回表示当前对象的字符串。(继承自 Object) |