using System; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Collections.Generic; namespace X509Cert { public class PKCS12 { public static X509Certificate2[] Read(string filename, string password) { FileStream stream = new FileStream(filename, FileMode.Open); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); WIN32.CRYPT_DATA_BLOB cryptdata = new WIN32.CRYPT_DATA_BLOB(); cryptdata.cbData = buffer.Length; cryptdata.pbData = Marshal.AllocHGlobal(cryptdata.cbData); Marshal.Copy(buffer, 0, cryptdata.pbData, buffer.Length); IntPtr hMemStore = WIN32.PFXImportCertStore(ref cryptdata, password, WIN32.CRYPT_USER_KEYSET); Marshal.FreeHGlobal(cryptdata.pbData); uint provinfosize = 0; List certs = new List(); IntPtr certHandle = IntPtr.Zero; while ((certHandle = WIN32.CertEnumCertificatesInStore(hMemStore, certHandle)) != IntPtr.Zero) { if (WIN32.CertGetCertificateContextProperty(certHandle, WIN32.CERT_KEY_PROV_INFO_PROP_ID, IntPtr.Zero, ref provinfosize)) { IntPtr info = Marshal.AllocHGlobal((int)provinfosize); if (WIN32.CertGetCertificateContextProperty(certHandle, WIN32.CERT_KEY_PROV_INFO_PROP_ID, info, ref provinfosize)) { var certData = new X509Certificate2(certHandle).Export(X509ContentType.SerializedCert); certs.Add(new X509Certificate2(certData)); } Marshal.FreeHGlobal(info); } } Marshal.FreeHGlobal(hMemStore); return certs.ToArray(); } } }