2016-09-30 85 views
1

如何簽名包含常規文本的文件?如何簽署文本文件或任何其他xml

我馬上解釋。
我在C#中創建了一個應用程序,它允許您使用USB令牌上的證書籤署XML文檔。我從集合中選擇一個證書:

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(xmlString); 
X509Certificate2 myCert = null; 
X509Store st = new X509Store(); 
st.Open(OpenFlags.ReadOnly); 
X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(st.Certificates, "Choose certificate:", "", X509SelectionFlag.SingleSelection); 

然後我用的一切,我走到這一步,簽署這個XML文檔:

public static string SignXmlWithCertificate(XmlDocument Document, X509Certificate2 cert) 
    { 
     SignedXml signedXml = new SignedXml(Document); 
     // pure black magic 
     signedXml.SigningKey = cert.PrivateKey; 

     // Create a reference to be signed. 
     Reference reference = new Reference(); 
     reference.Uri = ""; 

     // Add an enveloped transformation to the reference.   
     XmlDsigEnvelopedSignatureTransform env = 
      new XmlDsigEnvelopedSignatureTransform(true); 
     reference.AddTransform(env); 

     //canonicalize 
     XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); 
     reference.AddTransform(c14t); 

     KeyInfo keyInfo = new KeyInfo(); 
     KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert); 
     KeyInfoName kin = new KeyInfoName(); 
     kin.Value = "Public key of certificate"; 
     RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key; 
     RSAKeyValue rkv = new RSAKeyValue(rsaprovider); 
     keyInfo.AddClause(kin); 
     keyInfo.AddClause(rkv); 
     keyInfo.AddClause(keyInfoData); 
     signedXml.KeyInfo = keyInfo; 

     // Add the reference to the SignedXml object. 
     signedXml.AddReference(reference); 

     // Compute the signature. 
     signedXml.ComputeSignature(); 

     // Get the XML representation of the signature and save 
     // it to an XmlElement object. 
     XmlElement xmlDigitalSignature = signedXml.GetXml(); 

     Document.DocumentElement.AppendChild(
      Document.ImportNode(xmlDigitalSignature, true)); 

     return Document.OuterXml; 
    } 

實際問題
我的問題是,該怎麼辦與純文本文件一樣。我的意思是當我使用簽名軟件時,我可以看到幾乎相同的文件,除了文本(而不是xml)是用base64編碼的。
我在C#中使用哪些方法來簽署常規文件?我無法將它加載到XmlDocument,因爲它只是不是XML。

我知道你會問無論如何,所以是的。我試過在谷歌中找到它,但我想我只是用錯誤的詞來搜索它。所以,任何幫助感激。

+0

看看是否有幫助:https://blogs.msdn.microsoft.com/alejacma/2008/06/25/how-to-sign-and-verify-the-signature-with-net-and-a- certificate-c/ – neo

回答

-4

您可以在MS word和Open Office中籤署一個.txt文件。確切的方法將取決於您使用的版本。

+0

嗯,很抱歉,MS Word或Open Office與C#應用程序有什麼關係?如果我只想做一次,我可以使用USB令牌/證書提供的軟件。但我正在嘗試創建一個應用程序來重複執行它。 – Kedor

0

爲了使用數字簽名簽署文件,必須有一個可用於區分文件數據和簽名塊的模式。例如,腳本文本文件(比如.ps1,.vbs,.js等)具有這樣的架構,其中籤名放置在文件末尾的註釋塊中。類似的方法用於複雜的文檔類型,.pdf,.docx等。

因爲文本文件沒有這樣的模式,您將不得不引入新的文件類型並定義規則來定義文件內容和簽名結構。

如果您無法對文本文件執行規則,則可以使用目錄簽名。在這種情況下,您將文本文件哈希放入目錄文件(.cat)並對其進行數字簽名。

相關問題