C# 如何对文本文件或xml以外的任何文件进行签名

C# 如何对文本文件或xml以外的任何文件进行签名,c#,x509certificate,C#,X509certificate,如何对包含常规文本的文件进行签名 我马上解释。 我用C创建了一个应用程序,它允许您使用USB令牌上的证书对XML文档进行签名。我从集合中选择一个证书: XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlString); X509Certificate2 myCert = null; X509Store st = new X509Store(); st.Open(OpenFlags.ReadOnly); X509Certificate2Coll

如何对包含常规文本的文件进行签名

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


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

您可以在MS word中签署.txt并打开Office。确切的方法取决于您使用的版本。

要使用数字签名对文件进行签名,必须有一个可用于区分文件数据和签名块的模式。例如,脚本文本文件,.ps1、.vbs、.js等都有这样的模式,其中签名放在文件末尾的注释块中。类似的方法用于复杂的文档类型、.pdf、.docx等

因为文本文件没有这样的模式,所以必须引入新的文件类型并定义规则来定义文件内容和签名结构


如果无法对文本文件强制执行规则,则可以使用目录签名。在本例中,您将文本文件散列放入catalog file.cat并对其进行数字签名。

很抱歉,MS word或Open Office与C应用程序有什么关系?如果我只想做一次,我可以使用USB令牌/证书提供的软件。但我正在尝试创建一个应用程序来反复执行此操作。看看这是否有帮助: