如何签署XML文件? [英] How can I sign an XML file?
本文介绍了如何签署XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码:
using System;
using System.Security.Cryptography;
using System.Xml;
namespace FirmaXML
{
class Program
{
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);
}
}
public static void SignXml(XmlDocument xmlDoc, RSA Key)
{
// Check arguments.
if (xmlDoc == null)
throw new ArgumentException("xmlDoc");
if (Key == null)
throw new ArgumentException("Key");
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(xmlDoc);
// Add the key to the SignedXml document.
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.
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
}
}
}
但是在行中"SignedXml signedXml = new SignedXml(xmlDoc);" ;它给了我一个错误,有谁知道我能做些什么来解决它?
But in the line "SignedXml signedXml = new SignedXml (xmlDoc);" It gives me an error, does anyone know what I can do to solve it?
推荐答案
< p style ="margin-bottom:12pt"> 嗨aus2302,
欢迎来到MSDN论坛。
请参阅您的代码和说明,看来你请遵循以下文档:
如何:使用数字签名签署XML文档并请检查
编译代码
- 要编译此示例,您需要包含参考到&的系统.Security.dll 。
- 包括以下命名空间: System.Xml , System.Security.Cryptography ,
和 系统。 Security.Cryptography.Xml 。
- To compile this example, you need to include a reference to System.Security.dll.
- Include the following namespaces: System.Xml, System.Security.Cryptography, and System.Security.Cryptography.Xml.
您似乎错过了名称空间:
System.Security.Cryptography.Xml
如下所示:
It seems you missing the namespaces: System.Security.Cryptography.Xml as below:
最好的问候,
Sara
这篇关于如何签署XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文