我正在尝试使用x.509证书签署XML文件,我可以使用私钥对文档进行签名,然后使用CheckSignature方法(它有一个接收证书作为参数的重载)来验证签名。
问题是验证签名的用户必须拥有证书,我担心的是,如果用户拥有证书,那么他可以访问私钥,据我所知,这是私有的,应该只有给签名的用户。
我错过了什么?
感谢您的帮助。
答案 0 :(得分:19)
在.NET中,如果从.pfx文件获得X509证书,请执行以下操作:
X509Certificate2 certificate = new X509Certificate2(certFile, pfxPassword);
RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider) certificate.PrivateKey;
然后您可以像这样导出公钥部分:
rsaCsp.ToXmlString(false);
“虚假”部分说,只出口公共部分,不出口私人部分。 (RSA.ToXmlString的文件)
然后在验证应用程序中,使用
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
csp.FromXmlString(PublicKeyXml);
bool isValid = VerifyXml(xmlDoc, rsa2);
VerifyXml调用CheckSignature()
。它看起来像这样:
private Boolean VerifyXml(XmlDocument Doc, RSA Key)
{
// Create a new SignedXml object and pass it
// the XML document class.
var signedXml = new System.Security.Cryptography.Xml.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.");
}
// Though it is possible to have multiple signatures on
// an XML document, this app 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);
}
答案 1 :(得分:5)
任何证书都有公共部分和私有部分。你只发送公共部分。只需在浏览器中打开任何启用SSL的网站,单击挂锁符号即可查看其证书。
答案 2 :(得分:0)
首先,您需要确保证书.pfx或.cer 您正在使用的是用于签名目的。
You can check same in General Tab of a certificate *.Proves your identity to a remote computer *.Protects e-mail messages *.Allows data to be signed with the current time *.Allows data on disk to be encrypted *.2.16.356.100.2 **Document Signing**
用C#编写/验证XmlDocument的完整控制台应用程序是here。