如何签署文本文件,或xml以外的任何文件

本文关键字:文件 任何 xml 何签署 文本 | 更新日期: 2023-09-27 18:09:32

如何签署包含常规文本的文件?

我马上解释。
我用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。

我知道你无论如何都会问,所以是的。我试着在谷歌上找到它,但我想我只是用了错误的词来搜索它。非常感谢大家的帮助

如何签署文本文件,或xml以外的任何文件

为了对文件进行数字签名,必须有一个可以用来区分文件数据和签名块的模式。例如,脚本文本文件(例如,.ps1、.vbs、.js等)具有这样的模式,其中签名位于文件末尾的注释块中。类似的方法也用于复杂的文档类型,如。pdf、。docx等。

由于文本文件没有这样的模式,您将不得不引入新的文件类型并定义规则来定义文件内容和签名结构。

如果不能对文本文件强制执行规则,则可以使用目录签名。在本例中,将文本文件散列放在目录文件(.cat)中并对其进行数字签名。

您可以在MS word和Open Office中签署。txt文件。具体方法取决于您使用的版本。