static void AddCertificateToStore(CertificateSystemStoreLocation storeLocation, string storeName, SafeCertContextHandle certificate) { try { using (var store = CertOpenStore(CertStoreProviders.CERT_STORE_PROV_SYSTEM, IntPtr.Zero, IntPtr.Zero, storeLocation, storeName)) { var storeContext = IntPtr.Zero; if (!CertAddCertificateContextToStore(store, certificate, AddCertificateDisposition.CERT_STORE_ADD_NEW, ref storeContext)) { var error = Marshal.GetLastWin32Error(); if (error == (int)CapiErrorCode.CRYPT_E_EXISTS) { Log.Info("Certificate already exists in store."); return; } throw new CryptographicException(error); } var subjectName = CertificatePal.GetSubjectName(certificate); Log.Info($"Imported certificate '{subjectName}' into store '{storeName}'"); } } catch (Exception ex) { throw new Exception("Could not add certificate to store", ex); } }
static SafeCertContextHandle ImportPfxToStore(CertificateSystemStoreLocation storeLocation, string storeName, byte[] pfxBytes, string password, bool useUserKeyStore, bool privateKeyExportable) { var pfxImportFlags = useUserKeyStore ? PfxImportFlags.CRYPT_USER_KEYSET : PfxImportFlags.CRYPT_MACHINE_KEYSET; if (privateKeyExportable) { pfxImportFlags = pfxImportFlags | PfxImportFlags.CRYPT_EXPORTABLE; } var certificates = GetCertificatesFromPfx(pfxBytes, password, pfxImportFlags); // Import the first certificate into the specified store AddCertificateToStore(storeLocation, storeName, certificates.First()); // Any other certificates in the chain are imported into the Intermediate Authority and Root stores // of the Local Machine (importing into user CA stores causes a security-warning dialog to be shown) for (var i = 1; i < certificates.Count; i++) { var certificate = certificates[i]; // If it is the last certificate in the chain and is self-signed then it goes into the Root store if (i == certificates.Count - 1 && IsSelfSigned(certificate)) { AddCertificateToStore(CertificateSystemStoreLocation.LocalMachine, RootAuthorityStoreName, certificate); continue; } // Otherwise into the Intermediate Authority store AddCertificateToStore(CertificateSystemStoreLocation.LocalMachine, IntermediateAuthorityStoreName, certificate); } return(certificates.First()); }
bool CertEnumSystemStore(CertificateSystemStoreLocation dwFlags, IntPtr notUsed1, IntPtr notUsed2, CertEnumSystemStoreCallBackProto fn);
public static extern SafeCertStoreHandle CertOpenStore(CertStoreProviders lpszStoreProvider, IntPtr notUsed, IntPtr notUsed2, CertificateSystemStoreLocation location, [MarshalAs(UnmanagedType.LPWStr)] string storeName);