public static extern SafeCertStoreHandle PFXImportCertStore(ref CryptoData pPfx,
                                                             [MarshalAs(UnmanagedType.LPWStr)] string szPassword, PfxImportFlags dwFlags);
        static IList <SafeCertContextHandle> GetCertificatesFromPfx(byte[] pfxBytes, string password, PfxImportFlags pfxImportFlags)
        {
            // Marshal PFX bytes into native data structure
            var pfxData = new CryptoData
            {
                cbData = pfxBytes.Length,
                pbData = Marshal.AllocHGlobal(pfxBytes.Length)
            };

            Marshal.Copy(pfxBytes, 0, pfxData.pbData, pfxBytes.Length);

            var certificates = new List <SafeCertContextHandle>();

            try
            {
                using (var memoryStore = PFXImportCertStore(ref pfxData, password, pfxImportFlags))
                {
                    if (memoryStore.IsInvalid)
                    {
                        throw new CryptographicException(Marshal.GetLastWin32Error());
                    }

                    var certificatesToImport = GetCertificatesToImport(pfxBytes, password);

                    foreach (var certificate in certificatesToImport)
                    {
                        var thumbprint = CalculateThumbprint(certificate);
                        // Marshal PFX bytes into native data structure
                        var thumbprintData = new CryptoData
                        {
                            cbData = thumbprint.Length,
                            pbData = Marshal.AllocHGlobal(thumbprint.Length)
                        };

                        Marshal.Copy(thumbprint, 0, thumbprintData.pbData, thumbprint.Length);

                        var certificateHandle = CertFindCertificateInStore(memoryStore,
                                                                           CertificateEncodingType.Pkcs7OrX509AsnEncoding,
                                                                           IntPtr.Zero, CertificateFindType.Sha1Hash, ref thumbprintData, IntPtr.Zero);

                        if (certificateHandle == null || certificateHandle.IsInvalid)
                        {
                            throw new Exception("Could not find certificate");
                        }

                        certificates.Add(certificateHandle);

                        Marshal.FreeHGlobal(thumbprintData.pbData);
                    }

                    return(certificates);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not read PFX", ex);
            }
            finally
            {
                Marshal.FreeHGlobal(pfxData.pbData);
            }
        }