C# – How to read Pkcs#7 certificate chain from file/stream in C#

cpkcs#7x509certificate2

I have two certificates that I saved to disk. One is a certificate with private key that I exported as a .pfx file, the other one is a certificate that I saved including its certificate chain as a PKCS#7 file ("certchain.p7b").

In C# I can now load the .pfx file with

  var cert = new X509Certificate2(myPfxFileStream); 

(myPfxFileStream is a FileStream opened to the .pfx File for reading), however trying the same thing with the PKCs#7 Certificate fails in a CryptoGraphicException "Der Indexwert ist ungültig" which translates to "invalid index value".

I assume I have to parse PKCS#7 differently (it contains a chain, not a single certificate!), but how?

(Oh, by the way: Currently I have no passwords on those certficiates)

Best Answer

You will want to use the SignedCms class in the System.Security.Cryptography.Pkcs namespace.

This blog entry will show you how to use the class:

link update 2021: https://docs.microsoft.com/en-us/archive/blogs/shawnfa/enveloped-pkcs-7-signatures

original link: http://blogs.msdn.com/shawnfa/archive/2006/02/27/539990.aspx

You basically will call the Decode method, passing the bytes representing the PKCS file.