如何在Windows(C#/ C ++)上验证和提取PKCS#7文件内容 [英] How to validate and extract PKCS#7 file content on Windows (C#/C++)

查看:191
本文介绍了如何在Windows(C#/ C ++)上验证和提取PKCS#7文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With signtool I can create a PKCS#7 file with the following command

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

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

I get a slightly larger file signed file with .p7 appended. I can then verify it with

signtool verify /p7 myfile.zip.p7

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

But what is the recommended way to verify the signature with code and then extract the data? The WinVerifyTrustEx function works fine with PE files, but doesn't like P7 files. It returns 2148204800 ("No Signature was present in the subject"). signtool is not redistributable and it doesn't have an option to extract the data.

推荐答案

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

Based on this other post, there is no out of the box support in .NET. But, I found that you can use the System.Security.Cryptography.Pkcs SignedData to validate but the content seems to be still encoded. So for extracting the actual message, use bouncycastle. I've tried the code below as a sample.

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();

    }   

这篇关于如何在Windows(C#/ C ++)上验证和提取PKCS#7文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆