在C#中,签署X.509证书的XML和检查签名(In C#, sign an xml with a

2019-06-27 00:57发布

我正在尝试注册使用X.509证书的XML文件,我可以用私钥签署该文件,然后使用CheckSignature方法(它具有接收证书作为参数的重载)来验证签名。

问题是,谁验证签名,用户必须有证书,我关心的是,如果用户拥有的证书,然后,他访问私钥,并按照我的理解,这是公开的,并且只提供给用户谁签署。

我在想什么?

谢谢你的帮助。

Answer 1:

在.NET中,如果你从一个.pfx文件,这样让你的X509证书:

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

然后您可以导出像这样的公共密钥部分:

 rsaCsp.ToXmlString(false);

“假”的部分说,只导出公共件,不导出私钥件。 (DOC为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);
}


Answer 2:

任何证书有一个公共的和私人的一部分。 你只送周围的公共部分。 只需打开浏览器中的任何启用SSL的网站,点击挂锁符号,并看看他们的证书。



Answer 3:

首先你需要确保该证书.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写在这里 。



文章来源: In C#, sign an xml with a x.509 certificate and check the signature