如何:验证 XML 文档的数字签名
更新:2007 年 11 月
可以使用 System.Security.Cryptography.Xml 命名空间中的类验证数字签名的 XML 数据。 使用 XML 数字签名 (XMLDSIG),您可以验证签名后的数据没有被更改。 有关 XMLDSIG 标准的更多信息,请参见位于 http://www.w3.org/TR/xmldsig-core/ 上的 WWW 联合会 (W3C) 规范。
此过程中的代码示例演示了如何验证包含在 <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