internal static X509Certificate2Collection GetCertificates(Cryptography.SafeCertStoreHandle safeCertStoreHandle) { X509Certificate2Collection collection = new X509Certificate2Collection(); IntPtr pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, IntPtr.Zero); while (pEnumContext != IntPtr.Zero) { X509Certificate2 certificate = new X509Certificate2(pEnumContext); collection.Add(certificate); pEnumContext = CAPI.CertEnumCertificatesInStore(safeCertStoreHandle, pEnumContext); } return(collection); }
internal static Cryptography.SafeCertStoreHandle ExportToMemoryStore(X509Certificate2Collection collection) { // // We need to Assert all StorePermission flags since this is a memory store and we want // semi-trusted code to be able to export certificates to a memory store. // #if !FEATURE_CORESYSTEM StorePermission sp = new StorePermission(StorePermissionFlags.AllFlags); sp.Assert(); #endif Cryptography.SafeCertStoreHandle safeCertStoreHandle = Cryptography.SafeCertStoreHandle.InvalidHandle; // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation. // By default, Archived certificates will not be included. safeCertStoreHandle = CAPI.CertOpenStore(new IntPtr(CAPI.CERT_STORE_PROV_MEMORY), CAPI.X509_ASN_ENCODING | CAPI.PKCS_7_ASN_ENCODING, IntPtr.Zero, CAPI.CERT_STORE_ENUM_ARCHIVED_FLAG | CAPI.CERT_STORE_CREATE_NEW_FLAG, null); if (safeCertStoreHandle == null || safeCertStoreHandle.IsInvalid) { throw new CryptographicException(Marshal.GetLastWin32Error()); } // // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get // applied to the original store. This has a limit of 99 links per cert context however. // foreach (X509Certificate2 x509 in collection) { if (!CAPI.CertAddCertificateLinkToStore(safeCertStoreHandle, x509.CertContext, CAPI.CERT_STORE_ADD_ALWAYS, Cryptography.SafeCertContextHandle.InvalidHandle)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } } return(safeCertStoreHandle); }