簡體   English   中英

在C#中,使用x.509證書簽署xml並檢查簽名

[英]In C#, sign an xml with a x.509 certificate and check the signature

我正在嘗試使用x.509證書簽署XML文件,我可以使用私鑰對文檔進行簽名,然后使用CheckSignature方法(它具有接收證書作為參數的重載)來驗證簽名。

問題是驗證簽名的用戶必須擁有證書,我擔心的是,如果用戶擁有證書,那么他可以訪問私鑰,據我所知,這是私有的,應該只對用戶可用誰簽字。

我錯過了什么?

謝謝你的幫助。

在.NET中,如果從.pfx文件獲得X509證書,如下所示:

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

然后你可以像這樣導出公鑰部分:

 rsaCsp.ToXmlString(false);

“虛假”部分說,只出口公共件,不出口私人件。 (doc for 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);
}

任何證書都有公共部分和私有部分。 你只發送公共部分。 只需在瀏覽器中打開任何啟用SSL的網站,單擊掛鎖符號即可查看其證書。

首先,您需要確保您使用的證書.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進行數字簽名/驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM