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

放肆的年华 提交于 2019-12-06 15:06:48
MichaelChan

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

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