SignedXml 类

定义

在核心 XML 签名对象上提供包装器,以帮助创建 XML 签名。

public ref class SignedXml
public class SignedXml
type SignedXml = class
Public Class SignedXml
继承
SignedXml

示例

下面的代码示例演示如何使用信封签名对整个 XML 文档进行签名和验证。

//
// 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", Key);

           // 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. This method does not  
    // save the public key within the XML file.  This file cannot be verified unless  
    // the verifying code has the key with which it was signed.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Load the passed XML file using its 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);

        // 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 against an asymmetric 
    // algorithm and return the result.
    public static Boolean VerifyXmlFile(String Name, RSA Key)
    {
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // 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(Key);
    }

    // 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.X509Certificates
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", Key)
         
         ' 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. This method does not  
   ' save the public key within the XML file.  This file cannot be verified unless  
   ' the verifying code has the key with which it was signed.
   Public Shared Sub SignXmlFile(FileName As String, SignedFileName As String, Key As RSA)
      ' Create a new XML document.
      Dim doc As New XmlDocument()
      
      ' Load the passed XML file using its 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)
      
      ' 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 against an asymmetric 
   ' algorithm and return the result.
   Public Shared Function VerifyXmlFile(Name As [String], Key As RSA) As [Boolean]
      ' Create a new XML document.
      Dim xmlDocument As New XmlDocument()
      
      ' 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(Key)
   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

下面的代码示例演示如何使用 enveloping 签名对 XML 文档的单个元素进行签名和验证。

//
// 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)
    {
        // Generate a signing key.
       RSA Key = RSA.Create();

       try
       {
           // Specify an element to sign.
           string[] elements =  { "#tag1" };

           // Sign an XML file and save the signature to a
           // new file.
           SignXmlFile("Test.xml", "SignedExample.xml", Key, elements);
           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);
       }
       finally
       {
           // Clear resources associated with the
           // RSA instance.
           Key.Clear();
       }
   }

    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string[] ElementsToSign)
    {
        // Check the arguments.
        if (FileName == null)
            throw new ArgumentNullException("FileName");
        if (SignedFileName == null)
            throw new ArgumentNullException("SignedFileName");
        if (Key == null)
            throw new ArgumentNullException("Key");
        if (ElementsToSign == null)
            throw new ArgumentNullException("ElementsToSign");

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

        // Loop through each passed element to sign
        // and create a reference.
        foreach (string s in ElementsToSign)
        {
            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = s;

            // 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)
    {
        // Check the arguments.
        if (Name == null)
            throw new ArgumentNullException("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();
    }
}
' 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



Module SignVerifyEnvelope



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

        Try
            ' Specify an element to sign. 
            Dim elements As String() = New String() {"#tag1"}

            ' Sign an XML file and save the signature to a 
            ' new file.
            SignXmlFile("Test.xml", "SignedExample.xml", Key, elements)
            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)
        Finally
            ' Clear resources associated with the 
            ' RSA instance.
            Key.Clear()
        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, ByVal ElementsToSign() As String)
        ' Check the arguments.  
        If FileName Is Nothing Then
            Throw New ArgumentNullException("FileName")
        End If
        If SignedFileName Is Nothing Then
            Throw New ArgumentNullException("SignedFileName")
        End If
        If Key Is Nothing Then
            Throw New ArgumentNullException("Key")
        End If
        If ElementsToSign Is Nothing Then
            Throw New ArgumentNullException("ElementsToSign")
        End If
        ' 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

        ' Loop through each passed element to sign 
        ' and create a reference.
        Dim s As String
        For Each s In ElementsToSign
            ' Create a reference to be signed.
            Dim reference As New Reference()
            reference.Uri = s

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

        ' 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]
        ' Check the arguments.  
        If Name Is Nothing Then
            Throw New ArgumentNullException("Name")
        End If
        ' 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
End Module

注解

此类 SignedXml 是万维网联盟 (W3C) XML 签名语法和处理规范的 .NET 实现,也称为 XMLDSIG (XML 数字签名)。 XMLDSIG 是一种基于标准的可互作方式,用于对 XML 文档或可从统一资源标识符(URI)寻址的所有或部分 XML 文档或其他数据进行签名和验证。

SignedXml每当需要以标准方式在应用程序或组织之间共享签名的 XML 数据时,请使用该类。 使用此类签名的任何数据都可以通过符合 W3C 规范的 XMLDSIG 实现进行验证。

SignedXml 允许创建以下三种类型的 XML 数字签名:

签名类型 Description
信封签名 签名包含在正在签名的 XML 元素中。
封装签名 签名的 XML 被包含在 <Signature> 元素中。
内部分离签名 签名和签名 XML 位于同一文档中,但两个元素均不包含另一个元素。

还有第四种签名称为外部分离签名,即数据和签名位于单独的 XML 文档中。 SignedXml 类不支持外部分离签名。

XML 签名的结构

XMLDSIG 创建一个 <Signature> 元素,其中包含 XML 文档的数字签名或其他可从 URI 寻址的数据。 该 <Signature> 元素可以选择包含有关在何处查找密钥的信息,该密钥将验证签名以及用于签名的加密算法。 基本结构如下所示:

<Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
      <Reference URI="">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
        <DigestValue>Base64EncodedValue==</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>AnotherBase64EncodedValue===</SignatureValue>
</Signature>

此结构的主要部分包括:

  • <CanonicalizationMethod> 元素

    指定将 Signature 元素从 XML/文本重写为字节用于签名验证的规则。 在 .NET 中,默认值是 http://www.w3.org/TR/2001/REC-xml-c14n-20010315,用于标识可信算法。 此元素由 SignedInfo.CanonicalizationMethod 属性表示。

  • <SignatureMethod> 元素

    指定用于生成签名和验证的算法,该算法应用于元素 <Signature> 以生成值 <SignatureValue>。 在前面的示例中,该值 http://www.w3.org/2000/09/xmldsig#rsa-sha1 标识 RSA PKCS1 SHA-1 签名。 由于 SHA-1 冲突问题,Microsoft建议基于 SHA-256 或更高版本的安全模型。 此元素由 SignatureMethod 属性表示。

  • <SignatureValue> 元素

    指定 <Signature> 元素的加密签名。 如果无法验证签名,那么<Signature> 块的某些部分可能已被篡改,文档因此被视为无效。 只要 <CanonicalizationMethod> 该值可信,此值就高度抵御篡改。 此元素由 SignatureValue 属性表示。

  • URI元素的<Reference>属性

    使用 URI 引用指定数据对象。 此属性由 Reference.Uri 属性表示。

    • 不指定 URI 属性(即将 Reference.Uri 属性设置为 null)意味着接收应用程序应知道对象的标识。 在大多数情况下,null URI 将引发异常。 除非应用程序与需要 URI 的协议进行互作,否则不要使用 null URI。

    • URI 属性设置为空字符串表示文档的根元素正在签名,这是一种信封签名形式。

    • URI如果属性值以 #开头,则该值必须解析为当前文档中的元素。 此表单可以与任何受支持的签名类型(信封签名、封装签名或内部分离签名)一起使用。

    • 任何其他情况均被视为外部资源分离签名,且不被 SignedXml 类支持。

  • <Transforms> 元素

    包含一个 <Transform> 元素的有序列表,这些元素描述了签名者获取经过摘要处理的数据对象的方式。 转换算法类似于规范化方法,但它不是重写<Signature>元素,而是重写元素URI<Reference>属性所标识的内容。 该 <Transforms> 元素由 TransformChain 类表示。

    • 每个转换算法都定义为采用 XML(XPath 节点集)或字节作为输入。 如果当前数据的格式与转换输入要求不同,则应用转换规则。

    • 每个转换算法都定义为生成 XML 或字节作为输出。

    • 如果最后一个转换算法的输出未以字节为单位定义(或未指定转换),则 规范化方法 将用作隐式转换(即使元素 <CanonicalizationMethod> 中指定了其他算法)。

    • 转换算法的http://www.w3.org/2000/09/xmldsig#enveloped-signature值被解释为规定从文档中删除<Signature>元素的规则。 否则,封装签名的验证程序将消化该文档(包括签名),但签名者会在应用签名之前消化该文档,从而导致不同的答案。

  • <DigestMethod> 元素

    标识要应用于由 URI 元素的 <Reference> 属性标识的转换内容的摘要(加密哈希)方法。 这个由Reference.DigestMethod属性表示。

选择规范化方法

除非与需要使用不同值的规范进行互作,否则我们建议使用默认的 .NET 规范化方法,即其值为 http://www.w3.org/TR/2001/REC-xml-c14n-200103151.0 的 XML-C14N 算法。 XML-C14N 1.0 算法需要得到 XMLDSIG 的所有实现的支持,特别是因为它是一种隐式的最终转换。

有一些版本的规范化算法支持保留注释。 不建议使用保留注释的规范化方法,因为它们违反了“所见即所签”原则。 也就是说,元素中的 <Signature> 注释不会更改签名的执行方式的处理逻辑,而只会更改签名值。 与弱签名算法结合使用时,允许包含注释会给攻击者提供不必要的自由来强制发生哈希冲突,从而使篡改的文档看起来是合法的。 在 .NET Framework 中,默认仅支持内置规范化程序。 要支持附加或自定义规范化程序,请参阅 SafeCanonicalizationMethods 属性。 如果文档使用不在 SafeCanonicalizationMethods 属性所表示的集合中的规范化方法,则 CheckSignature 方法将返回 false

注释

极其防御的应用程序可以删除它不希望签名者从 SafeCanonicalizationMethods 集合中使用的任何值。

参考值是否防止篡改?

是的,<Reference> 的值是防篡改的。 .NET 在处理任何 <SignatureValue> 值及其关联的转换之前,会先验证 <Reference> 的计算,并将提前中止以避免潜在的恶意处理指令。

选择要签名的元素

如果可能,建议对属性使用“” URI 值(或将 Uri 属性设置为空字符串)。 整个文档都会被用作摘要计算,这样整个文档就能得到防篡改的保护。

以定位点形式出现的 URI 值(例如 #foo)很常见,它指的是 ID 属性为“foo”的元素。 遗憾的是,这很容易被篡改,因为这只包括目标元素的内容,而不是上下文。 滥用这种区别被称为 XML 签名包装 (XSW)。

如果应用程序认为注释是语义(处理 XML 时不常见),则应使用“#xpointer(/)”而不是“”和“#xpointer(id('foo')”而不是“#foo”。 #xpointer 版本被解释为包括注释,而短名称表单不包括注释。

如果需要接受仅部分受保护的文档,并且想要确保所读取的内容与签名保护的内容相同,请使用 GetIdElement 方法。

有关 KeyInfo 元素的安全注意事项

可选 <KeyInfo> 元素(即 KeyInfo 属性)中的数据(即包含用于验证签名的密钥)不应受信任。

具体而言,当 KeyInfo 值表示裸 RSA、DSA 或 ECDSA 公钥时,尽管 CheckSignature 方法报告签名有效,文档可能已被篡改。 之所以发生这种情况,是因为执行篡改的实体只需生成新密钥,并使用该新密钥重新对被篡改的文档进行签名。 因此,除非应用程序验证公钥是否为预期值,否则文档应被视为被篡改。 这要求应用程序检查文档中嵌入的公钥,并针对文档上下文的已知值列表对其进行验证。 例如,如果认为某个已知用户可能颁发了该文档,则您可以根据该用户使用的已知密钥列表来检查密钥。

还可以使用 CheckSignatureReturningKey 该方法(而不是使用 CheckSignature 该方法)在处理文档后验证密钥。 但是,为了获得最佳安全性,应事先验证密钥。

或者,考虑尝试用户注册的公钥,而不是读取 <KeyInfo> 元素中的内容。

有关 X509Data 元素的安全注意事项

可选 <X509Data> 元素是元素的 <KeyInfo> 子元素,包含 X509 证书的一个或多个 X509 证书或标识符。 <X509Data> 元素中的数据从本质上讲也不应被信任。

使用嵌入 <X509Data> 元素验证文档时,.NET 仅验证数据是否解析为 X509 证书,该证书的公钥可用于验证文档签名。 与调用 CheckSignature 方法并将 verifySignatureOnly 参数设置为 false 不同,不执行撤销检查,不检查链信任,也不验证到期情况。 即使应用程序提取证书本身并将其传递给 CheckSignature 方法,并将 verifySignatureOnly 参数设置为 false,这仍然不足以防止文档被篡改。 仍需要验证证书是否适合正在签名的文档。

使用嵌入式签名证书可以提供有用的密钥轮换策略,无论是在 <X509Data> 节中还是在文档内容中。 使用此方法时,应用程序应手动提取证书并执行与以下类似的验证操作:

  • 证书是通过证书颁发机构(CA)直接或通过证书链颁发的,该证书颁发机构(CA)将其公共证书嵌入到应用程序中。

    仅使用 OS 提供的信任列表而不进行额外检查(例如已知的主题名称)不足以防止 SignedXml 中的篡改。

  • 该证书在文档签名时(或对于近实时文档处理而言的“当前时刻”)经核实未过期。

  • 对于由支持撤销功能的 CA 签发的长期有效证书,请验证该证书是否已被撤销。

  • 证书主题已验证为适用于当前文档。

选择转换算法

如果要与指定特定值(如 XrML)的规范进行互作,则需要遵循规范。 如果你有一个信封签名(如签名整个文档时),则需要使用 http://www.w3.org/2000/09/xmldsig#enveloped-signature (由 XmlDsigEnvelopedSignatureTransform 类表示)。 也可以指定隐式 XML-C14N 转换,但没有必要。 对于封装或分离的签名,无需进行任何变换。 隐式 XML-C14N 转换会自动处理所有内容。

随着Microsoft 安全公告 MS16-035 引入的安全更新,.NET限制默认情况下可在文档验证中使用的转换。 不受信任的转换会导致 CheckSignature 始终返回 false。 具体而言,由于恶意用户容易受到滥用,因此不允许需要其他输入的转换(在 XML 中指定为子元素)。 W3C 建议避免 XPath 和 XSLT 转换,这是受这些限制影响的两个主要转换。

外部引用存在的问题

如果应用程序未验证外部引用是否适合当前上下文,则可以以提供许多安全漏洞(包括拒绝服务、分布式反射拒绝服务、信息泄露、签名绕过和远程代码执行)的方式滥用它们。 即使应用程序验证了外部引用 URI,仍然存在资源被加载两次的问题:一次是当应用程序读取资源时,另一次是SignedXml读取它时。 由于无法保证应用程序读取和文档验证步骤具有相同的内容,因此签名不提供可信度。

鉴于外部引用的风险, SignedXml 在遇到外部引用时引发异常。 有关此问题的详细信息,请参阅.NET应用程序遇到异常错误

构造函数

名称 说明
SignedXml()

初始化 SignedXml 类的新实例。

SignedXml(XmlDocument)

从指定的 XML 文档初始化类的新实例 SignedXml

SignedXml(XmlElement)

从指定SignedXml对象初始化类的新实例XmlElement

字段

名称 说明
m_signature

表示 Signature 当前 SignedXml 对象的对象。

m_strSigningKeyName

表示要用于对对象进行签名的 SignedXml 已安装密钥的名称。

XmlDecryptionTransformUrl

表示 XML 模式解密转换的统一资源标识符(URI)。 此字段为常量。

XmlDsigBase64TransformUrl

表示 base 64 转换的统一资源标识符(URI)。 此字段为常量。

XmlDsigC14NTransformUrl

表示规范 XML 转换的统一资源标识符(URI)。 此字段为常量。

XmlDsigC14NWithCommentsTransformUrl

表示规范 XML 转换的统一资源标识符(URI),带有注释。 此字段为常量。

XmlDsigCanonicalizationUrl

表示 XML 数字签名的标准规范化算法的统一资源标识符(URI)。 此字段为常量。

XmlDsigCanonicalizationWithCommentsUrl

表示 XML 数字签名的标准规范化算法的统一资源标识符(URI),并包括注释。 此字段为常量。

XmlDsigDSAUrl

表示 XML 数字签名的标准 DSA 算法的统一资源标识符(URI)。 此字段为常量。

XmlDsigEnvelopedSignatureTransformUrl

表示信封签名转换的统一资源标识符(URI)。 此字段为常量。

XmlDsigExcC14NTransformUrl

表示独占 XML 规范化的统一资源标识符(URI)。 此字段为常量。

XmlDsigExcC14NWithCommentsTransformUrl

表示具有注释的独占 XML 规范化的统一资源标识符(URI)。 此字段为常量。

XmlDsigHMACSHA1Url

表示 XML 数字签名的标准 HMACSHA1 算法的统一资源标识符(URI)。 此字段为常量。

XmlDsigMinimalCanonicalizationUrl

表示 XML 数字签名的标准最小规范化算法的统一资源标识符(URI)。 此字段为常量。

XmlDsigNamespaceUrl

表示 XML 数字签名的标准命名空间的统一资源标识符(URI)。 此字段为常量。

XmlDsigRSASHA1Url

表示 XML 数字签名的标准 RSA 签名方法的统一资源标识符(URI)。 此字段为常量。

XmlDsigRSASHA256Url

表示 XML 数字签名的 SHA-256 签名方法变体的 RSA 统一资源标识符(URI)。 此字段为常量。

XmlDsigRSASHA384Url

表示 XML 数字签名的 SHA-384 签名方法变体的 RSA 统一资源标识符(URI)。 此字段为常量。

XmlDsigRSASHA512Url

表示 XML 数字签名的 SHA-512 签名方法变体的 RSA 统一资源标识符(URI)。 此字段为常量。

XmlDsigSHA1Url

表示 XML 数字签名的标准 SHA1 摘要方法的统一资源标识符(URI)。 此字段为常量。

XmlDsigSHA256Url

表示 XML 数字签名的标准 SHA256 摘要方法的统一资源标识符(URI)。 此字段为常量。

XmlDsigSHA384Url

表示 XML 数字签名的标准 SHA384 摘要方法的统一资源标识符(URI)。 此字段为常量。

XmlDsigSHA512Url

表示 XML 数字签名的标准 SHA512 摘要方法的统一资源标识符(URI)。 此字段为常量。

XmlDsigXPathTransformUrl

表示 XML 路径语言(XPath)的统一资源标识符(URI)。 此字段为常量。

XmlDsigXsltTransformUrl

表示 XSLT 转换的统一资源标识符(URI)。 此字段为常量。

XmlLicenseTransformUrl

表示用于规范签名的 XrML 许可证的许可证转换算法的统一资源标识符(URI)。

属性

名称 说明
EncryptedXml

获取或设置定义 EncryptedXml XML 加密处理规则的对象。

KeyInfo

获取或设置 KeyInfo 当前 SignedXml 对象的对象。

Resolver

设置当前 XmlResolver 对象。

SafeCanonicalizationMethods

获取显式允许其规范化算法的方法的名称。

Signature

Signature获取当前SignedXml对象的对象。

SignatureFormatValidator

获取将调用以验证 XML 签名的格式(而不是加密安全性)的委托。

SignatureLength

获取当前 SignedXml 对象的签名长度。

SignatureMethod

获取当前 SignedXml 对象的签名方法。

SignatureValue

获取当前 SignedXml 对象的签名值。

SignedInfo

SignedInfo获取当前SignedXml对象的对象。

SigningKey

获取或设置用于对对象进行签名 SignedXml 的非对称算法密钥。

SigningKeyName

获取或设置要用于对对象进行签名的 SignedXml 已安装密钥的名称。

方法

名称 说明
AddObject(DataObject)

将对象 DataObject 添加到要签名的对象列表中。

AddReference(Reference)

将对象 Reference 添加到 SignedXml 描述摘要方法、摘要值和转换的对象,以用于创建 XML 数字签名。

CheckSignature()

确定属性是否 Signature 使用签名中的公钥进行验证。

CheckSignature(AsymmetricAlgorithm)

确定属性是否 Signature 验证指定的键。

CheckSignature(KeyedHashAlgorithm)

确定属性是否 Signature 验证指定的消息身份验证代码 (MAC) 算法。

CheckSignature(X509Certificate2, Boolean)

确定属性是否 Signature 对指定 X509Certificate2 对象进行验证,以及证书是否有效(可选)。

CheckSignatureReturningKey(AsymmetricAlgorithm)

确定属性是否 Signature 使用签名中的公钥进行验证。

ComputeSignature()

计算 XML 数字签名。

ComputeSignature(KeyedHashAlgorithm)

使用指定的消息身份验证代码(MAC)算法计算 XML 数字签名。

Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetIdElement(XmlDocument, String)

XmlElement 指定对象返回具有指定 XmlDocument ID 的对象。

GetPublicKey()

返回签名的公钥。

GetType()

获取当前实例的 Type

(继承自 Object)
GetXml()

返回对象的 XML 表示形式 SignedXml

LoadXml(XmlElement)

SignedXml从 XML 元素加载状态。

MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
ToString()

返回一个表示当前对象的字符串。

(继承自 Object)

适用于

另请参阅