How to validate and extract PKCS#7 file content on Windows (C#/C++)

限于喜欢 提交于 2019-12-08 07:06:28

问题


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

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

signtool verify /p7 myfile.zip.p7

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.


回答1:


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

    }   


来源:https://stackoverflow.com/questions/32641809/how-to-validate-and-extract-pkcs7-file-content-on-windows-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!