【问题标题】:In C#, sign an xml with a x.509 certificate and check the signature在 C# 中,使用 x.509 证书对 xml 进行签名并检查签名
【发布时间】:2010-11-14 19:23:41
【问题描述】:

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

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

我错过了什么?

感谢您的帮助。

【问题讨论】:

    标签: c# xml digital-signature digital-certificate x509certificate2


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这正是我不清楚的地方。现在我知道我必须使用来自 X509Store 的证书来获取“签名者”证书,并使用 .cer 文件作为“验证者”。
    【解决方案2】:

    在 .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);
    }
    

    【讨论】:

    【解决方案3】:

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

    您可以在证书的常规选项卡中检查相同 *.向远程计算机证明您的身份 *.保护电子邮件 *.允许使用当前时间对数据进行签名 *.允许加密磁盘上的数据 *.2.16.356.100.2 **文件签名**

    用 C# 编写的用于对 XmlDocument 进行数字签名/验证的完整控制台应用程序是 here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2014-09-30
      • 2016-02-15
      • 2010-09-15
      相关资源
      最近更新 更多