【问题标题】:How to validate and extract PKCS#7 file content on Windows (C#/C++)如何在 Windows (C#/C++) 上验证和提取 PKCS#7 文件内容
【发布时间】:2015-09-17 23:59:59
【问题描述】:

使用 signtool 我可以使用以下命令创建一个 PKCS#7 文件

signtool sign /p7 <output dir> /p7co 0 /tr <ts server> /td SHA256 /f <pfx file> /p <pass> /a myfile.zip

我得到一个稍大的文件签名文件,附加了 .p7。 然后我可以验证它

signtool verify /p7 myfile.zip.p7

但是,用代码验证签名然后提取数据的推荐方法是什么? WinVerifyTrustEx 函数适用于 PE 文件,但不喜欢 P7 文件。它返回 2148204800(“主题中没有签名”)。 signtool 不可再分发,也没有提取数据的选项。

【问题讨论】:

    标签: c# winapi digital-signature


    【解决方案1】:

    基于另一个post,.NET 中没有开箱即用的支持。但是,我发现您可以使用 System.Security.Cryptography.Pkcs SignedData 进行验证,但内容似乎仍然是编码的。因此,要提取实际消息,请使用 bouncycastle。我已经尝试了下面的代码作为示例。

    static void Main(string[] args)
        {
            var encodedFile = File.ReadAllBytes(InPath);
    
            var signedData = new SignedCms();
            signedData.Decode(encodedFile);
            signedData.CheckSignature(true);
            if (!Verify(signedData))
                throw new Exception("No valid cert was found");
    
            var trueContent = new CmsSignedData(File.ReadAllBytes(InPath)).SignedContent;
    
            using (var str = new MemoryStream())
            {
                trueContent.Write(str);
                var zip = new ZipArchive(str, ZipArchiveMode.Read);
                zip.ExtractToDirectory(OutPath);
            }
    
    
        }
    
        static bool Verify(SignedCms signedData)
        {
            var myCetificates = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            myCetificates.Open(OpenFlags.ReadOnly);
            var certs = signedData.Certificates;
    
            return (from X509Certificate2 cert in certs
                select myCetificates.Certificates.Cast<X509Certificate2>()
                    .Any(crt => crt.Thumbprint == cert.Thumbprint))
                .Any();
    
        }   
    

    【讨论】:

    • 我使用了win32 api CryptVerifyMessageSignature 来验证。必须为此添加一个 DllImport。然后调用它两次以获取大小,然后再次调用以提取数据。
    猜你喜欢
    • 2014-02-22
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多