我正在尝试使用x.509证书对XML文件进行签名。 我可以使用私钥签署文档,然后使用CheckSignature方法(它有一个重载,接收证书作为参数)来验证签名。
问题是验证签名的用户必须拥有该证书。我的担忧是,如果用户拥有证书,则可以访问私钥,而据我所知,这是私有的,应仅向签署者提供。
我错在哪里了?
谢谢您的帮助。
我正在尝试使用x.509证书对XML文件进行签名。 我可以使用私钥签署文档,然后使用CheckSignature方法(它有一个重载,接收证书作为参数)来验证签名。
问题是验证签名的用户必须拥有该证书。我的担忧是,如果用户拥有证书,则可以访问私钥,而据我所知,这是私有的,应仅向签署者提供。
我错在哪里了?
谢谢您的帮助。
.NET中,如果你从.pfx文件获取X509证书,可以像这样:
X509Certificate2 certificate = new X509Certificate2(certFile, pfxPassword);
RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider) certificate.PrivateKey;
然后你可以这样导出公钥部分:
rsaCsp.ToXmlString(false);
“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);
}
首先,您需要确保您正在使用的证书.pfx或.cer是用于签名目的。
您可以在证书的“常规”选项卡中检查同样内容:
*.向远程计算机证明您的身份 *.保护电子邮件消息 *.允许使用当前时间对数据进行签名 *.允许加密磁盘上的数据 *.2.16.356.100.2 **文件签名**
这里编写了一个完整的控制台应用程序来以C#数字方式签名/验证XmlDocument here。