在C#中,使用x.509证书签署xml并检查签名

我正在尝试使用x.509证书签署XML文件,我可以使用私钥对文档进行签名,然后使用CheckSignature方法(它具有接收证书作为参数的重载)来validation签名。

问题是validation签名的用户必须拥有证书,我关心的是,如果用户拥有证书,那么他可以访问私钥,据我所知,这是私有的,应该只对用户可用谁签字。

我错过了什么?

谢谢你的帮助。

在.NET中,如果从.pfx文件获得X509证书,如下所示:

X509Certificate2 certificate = new X509Certificate2(certFile, pfxPassword); RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider) certificate.PrivateKey; 

然后你可以像这样导出公钥部分:

  rsaCsp.ToXmlString(false); 

“假”部分说,只出口公共件,不出口私人件。 (doc for RSA.ToXmlString )

然后在validation应用程序中,使用

  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  node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(Key); } 

任何证书都有公共部分和私有部分。 你只发送公共部分。 只需在浏览器中打开任何启用SSL的网站,单击挂锁符号即可查看其证书。

首先,您需要确保您使用的证书.pfx或.cer用于签名目的。

您可以在证书的“常规”选项卡中查看相同内容

 *。将您的身份certificate为远程计算机
 *。保护电子邮件
 *。允许使用当前时间签署数据
 *。允许加密磁盘上的数据
 * .2.16.356.100.2
 **文件签名**

在此处编写了一个完整的控制台应用程序,用于在C#中对XmlDocument进行数字签名/validation。