如何清理 X509 证书文件

How clean a X509 certified file

我做了一个例程,用 PKCS#7 X509 证书对一些专有二进制文件进行签名。例程运行得很好:

    public static byte[] SignFile(X509Certificate2Collection certs, byte[] data, bool Tipo_A3 = false)
    {
        try
        {
            ContentInfo content = new ContentInfo(data);
            SignedCms signedCms = new SignedCms(content, false);
            if (VerifySign(data))
            {
                signedCms.Decode(data);
            }
            foreach (X509Certificate2 cert in certs)
            {

                CmsSigner signer = new CmsSigner( cert);
                signer.IncludeOption = X509IncludeOption.WholeChain;
                signer.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;

                signer.SignedAttributes.Add(new Pkcs9SigningTime(System.DateTime.Now));

                if (Type_A3 == true)
                {
                    signedCms.ComputeSignature(signer, false);
                }
                else
                {
                    signedCms.ComputeSignature(signer);
                }

            }
            return signedCms.Encode();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
            return null;
        }

    }

我的问题与恢复原始信息有关。一个 1Kb 的文件将被转换成一个 ~8Kb 的文件,因为签名在这个文件中。

我需要读取文件中没有 signature/certificate 的数据 ,我的意思是,我需要在签名之前恢复原始数据 - 我没有不知道怎么做。

我看到签名文件在其原始内容之前和之后都有字节(我使用带有 "abcd" 的小型 TXT 文件进行了测试),但我不敢考虑之前的相同数据长度并在提取原始数据之后。

我知道我使用此功能获取原始内容,其中 DATA 是签名文件:

 using System;
 using System.Collections.Generic;
 using System.Security.Cryptography.X509Certificates;
 using System.Security.Cryptography.Pkcs;
 using System.IO;
 using System.Windows.Forms;

     public static Int VerifyContentInfo(byte[] data)
        {
           try
           {
            SignedCms signed = new SignedCms();
            signed.Decode(data);
            signed.CheckSignature(true);

            return signed.ContentInfo.Content.Length

           }
             catch
           {
             return null;
           }

        }

问题:即使知道签名文件中原始数据的长度,如何使用 .NET 函数安全地定位和提取它?

感谢您的帮助!

signed.ContentInfo.Content(你取其长度的值)是原始内容。