public static void CreateCertificate(string ip) { try { var cr = new CertificateRequest(new X500DistinguishedName("cn=ispy-local"), RSA.Create(), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); SubjectAlternativeNameBuilder subjectAlternativeNameBuilder = new SubjectAlternativeNameBuilder(); subjectAlternativeNameBuilder.AddIpAddress(IPAddress.Parse(ip)); var locals = MainForm.AddressListIPv4; foreach (var lip in locals) { subjectAlternativeNameBuilder.AddIpAddress(lip); } cr.CertificateExtensions.Add(subjectAlternativeNameBuilder.Build()); string pw = "123abc!!D"; var cert = cr.CreateSelfSigned(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddYears(+1)); var cert2 = new X509Certificate2(cert.Export(X509ContentType.Pfx, pw), pw); X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, "ispy-local", false); if (col.Count > 0) { store.RemoveRange(col); } store.Add(cert2); store.Close(); _sslCertificate = cert2; } catch (Exception ex) { Logger.LogException(ex, "X509 Create"); } }
protected virtual bool DestroyCertificate(X509Store store, string certificateName) { lock (store) { X509Certificate2Collection certificates = null; try { store.Open(OpenFlags.ReadWrite); string certificateSubject = string.Format("CN={0}, O={1}", certificateName, Issuer); certificates = FindCertificates(store, certificateSubject); if (certificates != null) { store.RemoveRange(certificates); certificates = FindCertificates(store, certificateSubject); } return(certificates == null); } finally { store.Close(); if (certificates == null && _certificateCache.ContainsKey(certificateName)) { _certificateCache.Remove(certificateName); } } } }
public bool ClearCertificateCache(bool bClearRoot) { _rwl.AcquireWriterLock(LOCK_TIMEOUT); _certificateCache.Clear(); if (bClearRoot) { _root = null; var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); try { store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); var roots = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, FIDDLER_ROOT_DN, true); store.RemoveRange(roots); } catch { return(false); } finally { store.Close(); } } _rwl.ReleaseWriterLock(); return(true); }
/// <summary> /// Removes a certificate from the store. Cleanup purposes. /// </summary> /// <param name="certificateName"></param> /// <param name="certificateStoreLocation"></param> /// <returns></returns> internal static void RemoveCertificate(string certificateName, StoreLocation certificateStoreLocation) { Assert.False(string.IsNullOrWhiteSpace(certificateName), "FAILED: certificateName should not be null or empty."); X509Store certStore = null; try { certStore = new X509Store(StoreName.My, certificateStoreLocation); certStore.Open(OpenFlags.ReadWrite); X509Certificate2Collection certificateCollection = certStore.Certificates.Find(X509FindType.FindBySubjectName, certificateName, validOnly: false); if (certificateCollection != null && certificateCollection.Count > 0) { certStore.RemoveRange(certificateCollection); } } finally { if (certStore != null) { certStore.Close(); } } }
private static void RemoveExpiredAndDuplicateCertificates(X509Store store) { var certs = GetDomainCertificates(store); var toRemove = new X509Certificate2Collection(); foreach (var cert in certs) { if (cert.NotAfter <= DateTime.Now) { Console.WriteLine("The certificate has expired, removing it from store"); toRemove.Add(cert); } } foreach (var cert in certs) { if (certs.Count - toRemove.Count == 1) { break; } if (toRemove.Contains(cert)) { continue; } Console.WriteLine("The certificate is a duplicate, removing it from store"); toRemove.Add(cert); } store.RemoveRange(toRemove); }
/// <summary> /// Remove certificate by name from Local User Certificate Store /// </summary> /// <param name="certificateName">The name of the certificate to remove.</param> /// <returns>Object { bool Success, CryptographicException Error }</returns> public static LocalStoreResult RemoveFromLocalUser(string certificateName) { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); X509Certificate2Collection certificatesToDelete = store.Certificates.Find(X509FindType.FindBySubjectName, certificateName, false); if (certificatesToDelete.Count != 0) { X509Chain ch = new X509Chain(); ch.Build(certificatesToDelete[0]); X509Certificate2Collection allCertsInChain = new X509Certificate2Collection(); foreach (X509ChainElement el in ch.ChainElements) { allCertsInChain.Add(el.Certificate); } store.RemoveRange(allCertsInChain); } } return(new LocalStoreResult { Success = true }); }
public bool DestroyCertificates(X509Store store) { lock (store) { try { store.Open(OpenFlags.ReadWrite); X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindByIssuerName, Issuer, false); store.RemoveRange(certificates); IEnumerable <string> subjectNames = certificates .Cast <X509Certificate2>().Select(c => c.GetNameInfo(X509NameType.SimpleName, false)); foreach (string subjectName in subjectNames) { if (!_certificateCache.ContainsKey(subjectName)) { continue; } _certificateCache.Remove(subjectName); } return(true); } catch { return(false); } finally { store.Close(); } } }
public static void RemoveCertificate(string serial, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.CurrentUser) { if (String.IsNullOrEmpty(serial)) { throw new ArgumentNullException("serial"); } X509Store store = null; try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); var existings = store.Certificates.Find(X509FindType.FindBySerialNumber, serial, false); if (existings.Count == 0) { return; } store.RemoveRange(existings); } finally { if (store != null) { store.Close(); } } }
public void AddOrReplaceToStore(X509Certificate2 certificate, AppCertificates id_store) { X509Store store = new X509Store("AutoBetCertificates", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.RemoveRange(store.Certificates.Find(X509FindType.FindByApplicationPolicy, certificate.FriendlyName, false)); store.Add(certificate); }
public void RemoveRange_OpenReadOnly_Unexisting() { X509Store xs = new X509Store("ReadOnlyStore"); xs.Open(OpenFlags.ReadOnly); // note: cert1 wasn't present, RemoveRange "succeed" xs.RemoveRange(coll); }
public void Dispose() { using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadWrite)) { var certs = store.Certificates.Find(X509FindType.FindByThumbprint, TestCertificateValues.Thumbprint, false); store.RemoveRange(certs); store.Close(); } }
private static void CleanupCertificates() { using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadWrite); store.RemoveRange(store.Certificates.Find(X509FindType.FindBySubjectName, "CN=SigningKeysLoaderTest", validOnly: false)); store.Close(); } }
public static bool UninstallCertificate(string thumb) { var col = Store.Certificates.Find(X509FindType.FindByThumbprint, thumb.ToUpper(), false); if (col != null && col.Count > 0) { Store.RemoveRange(col); } return(true); }
public void RemoveRange_Empty_Certificate() { X509Store xs = new X509Store("ReadWriteStore"); xs.Open(OpenFlags.ReadWrite); // note: impossible to add cert_empty, so we add something else // to be sure we'll follow the complete code path (loop) of removal xs.AddRange(coll); xs.RemoveRange(new X509Certificate2Collection(cert_empty)); }
public void RemoveRange_OpenReadOnly_Existing() { X509Store xs = new X509Store("ReadWriteStore"); xs.Open(OpenFlags.ReadWrite); xs.AddRange(coll); xs.Close(); xs.Open(OpenFlags.ReadOnly); xs.RemoveRange(coll); }
private static void Main(string[] args) { Task.Run(async() => { Console.WriteLine("Enter PIN: "); string pin = Console.ReadLine(); WebRequestHandler handler = new WebRequestHandler(); handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); using (HttpClient client = new HttpClient(handler, true)) { client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort)); X509Store store = null; try { var response = await client.GetAsync("certs/" + pin); response.EnsureSuccessStatusCode(); byte[] rawCert = await response.Content.ReadAsByteArrayAsync(); X509Certificate2Collection certs = new X509Certificate2Collection(); certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet); store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection oldCerts = new X509Certificate2Collection(); foreach (var cert in certs) { oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false)); } store.RemoveRange(certs); store.AddRange(certs); store.Close(); Console.WriteLine("Success"); } catch (HttpRequestException e) { Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated."); } finally { if (store != null) { store.Close(); } } } }).Wait(); }
static void Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Requires <Cert StoreName> <pfxfile> <friendlyname> and <password> arguments"); return; } string certStoreName = args[0]; string pfxFile = args[1]; string friendlyName = args[2]; string password = args[3]; X509Store store = new X509Store(certStoreName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); var newCert = new X509Certificate2(pfxFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); newCert.FriendlyName = friendlyName; store.Add(newCert); if (File.Exists("previousHash.txt") && File.Exists("previousHash.bin")) { var oldHashText = File.ReadAllText("previousHash.txt").Trim(); if (oldHashText == newCert.GetCertHashString()) { return; } var oldCert = store.Certificates.Find(X509FindType.FindByThumbprint, oldHashText, false); ServerManager mgr = new ServerManager(); foreach (Site s in mgr.Sites) { Console.WriteLine(s.Name); foreach (var b in s.Bindings.Where(x => x.Protocol == "https" && x.CertificateHash.SequenceEqual(File.ReadAllBytes("previousHash.bin")))) { b.CertificateHash = newCert.GetCertHash(); b.CertificateStoreName = certStoreName; b.SetAttributeValue("certificateStoreName", certStoreName); b.SetAttributeValue("certificateHash", newCert.GetCertHashString()); } } mgr.CommitChanges(); store.RemoveRange(oldCert); store.Close(); store.Dispose(); } File.WriteAllBytes("previousHash.bin", newCert.GetCertHash()); File.WriteAllText("previousHash.txt", newCert.GetCertHashString()); }
public void RemoveRange_Certificate_OK() { X509Store xs = new X509Store("ReadWriteStore"); xs.Open(OpenFlags.ReadWrite); xs.AddRange(coll); int countBeforeRemove = xs.Certificates.Count; xs.RemoveRange(coll); Assert.AreEqual(countBeforeRemove - coll.Count, xs.Certificates.Count); }
static void RemoveCertificatesFromStore(string cert , string password , StoreLocation loc) { //Import the pfx certificates X509Certificate2Collection certificates = new X509Certificate2Collection() ; certificates.Import( cert , password , X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); //Add the Certificate X509Store store = new X509Store( storeName , loc) ; // , "Cool Store" ) ; store.Open( OpenFlags.ReadWrite ) ; store.RemoveRange( certificates ) ; store.Close() ; }
private static void DeleteOldCertificatesIfFound(X509Store store, X509Certificate2 newCertificate) { var subject = newCertificate.GetNameInfo(X509NameType.SimpleName, false); if (subject == null) { return; } var certificateCollection = store.Certificates.Find(X509FindType.FindBySubjectName, subject, false); store.RemoveRange(certificateCollection); }
/// <summary> /// Remove the KAZ certs /// </summary> private void RemoveKAZrootCerts() { var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); foreach (string sThumb in _sCertThumb) { X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, sThumb, false); X509Chain ch = new X509Chain(); if (col.Count > 0) { ch.Build(col[0]); X509Certificate2Collection allCertsInChain = new X509Certificate2Collection(); foreach (X509ChainElement el in ch.ChainElements) { allCertsInChain.Add(el.Certificate); } store.RemoveRange(allCertsInChain); } } store.Close(); store = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); foreach (string sThumb in _sCertThumb) { X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, sThumb, false); X509Chain ch = new X509Chain(); if (col.Count > 0) { ch.Build(col[0]); X509Certificate2Collection allCertsInChain = new X509Certificate2Collection(); foreach (X509ChainElement el in ch.ChainElements) { allCertsInChain.Add(el.Certificate); } store.RemoveRange(allCertsInChain); } } store.Close(); DetectCerts(false); }
static void RemoveCertificatesFromStore(string cert, string password, StoreLocation loc) { //Import the pfx certificates X509Certificate2Collection certificates = new X509Certificate2Collection(); certificates.Import(cert, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); //Add the Certificate X509Store store = new X509Store(storeName, loc); // , "Cool Store" ) ; store.Open(OpenFlags.ReadWrite); store.RemoveRange(certificates); store.Close(); }
public static X509Store CreateCertStore(params string[] certPaths) { X509Store store = new X509Store("test", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.RemoveRange(store.Certificates); foreach (string certPath in certPaths) { X509Certificate2 certificate = new X509Certificate2(Path.Combine(TestSetup.LocalPath, certPath)); store.Add(certificate); } return(store); }
void RemoveAll(StoreName storeName) { X509Store store = null; try { store = new X509Store(storeName, MachineContext ? StoreLocation.LocalMachine : StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); var crtToDelete = store.Certificates.OfType <X509Certificate2>().Where(crt => thumbprints.Contains(crt.Thumbprint)).ToArray(); store.RemoveRange(new X509Certificate2Collection(crtToDelete)); RemovedCertificates += crtToDelete.Length; store.Close(); } finally { store?.Close(); } }
internal static void removeFiddlerGeneratedCerts() { if (oCertProvider != null) { oCertProvider.ClearCertificateCache(); } else { lock (oRootCertCreationLock) { string sFullSubject = string.Format("CN={0}{1}", CONFIG.sMakeCertRootCN, CONFIG.sMakeCertSubjectO); X509Certificate2Collection certificates = FindCertsBySubject(StoreName.Root, StoreLocation.CurrentUser, sFullSubject); if (certificates.Count > 0) { X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); try { store.RemoveRange(certificates); } catch { } store.Close(); } certificates = FindCertsByIssuer(StoreName.My, sFullSubject); if (certificates.Count > 0) { X509Store store2 = new X509Store(StoreName.My, StoreLocation.CurrentUser); store2.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); try { store2.RemoveRange(certificates); } catch { } store2.Close(); } } } }
private static void RemoveCertificate(string thumbprint, StoreName storeName, StoreLocation storeLocation) { var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); Console.WriteLine($"Removing certificate '{thumbprint}' from store."); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if (certificates.Count > 0) { throw new ArgumentNullException($"Unable to find certificate '{thumbprint}' from store."); } store.RemoveRange(certificates); Console.WriteLine("Done."); store.Close(); }
/// <summary> /// Removes the cert. /// </summary> /// <param name="storeName">Name of the store.</param> /// <param name="storeLoc">The store loc.</param> /// <param name="fType">Type of the f.</param> /// <param name="findValue">The find value.</param> public static void RemoveCert(string storeName, StoreLocation storeLoc, X509FindType fType, object findValue) { var loc = new X509Store(storeName, storeLoc); loc.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly); try { var col = loc.Certificates.Find(fType, findValue, false); if (col == null || col.Count == 0) { return; } loc.RemoveRange(col); } finally { loc.Close(); } }
private static void UninstallAllCertificatesByIssuer(StoreName storeName, StoreLocation storeLocation, Dictionary <string, CertificateCacheEntry> cache, string issuerDistinguishedName) { lock (s_certificateLock) { X509Store store = null; try { // We assume Bridge is running elevated store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); var collection = store.Certificates.Find(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName, false); Trace.WriteLine(string.Format("[CertificateManager] Forcibly removing {0} certificates from store where:", collection.Count)); Trace.WriteLine(string.Format(" {0} = {1}", "StoreName", storeName)); Trace.WriteLine(string.Format(" {0} = {1}", "StoreLocation", storeLocation)); Trace.WriteLine(string.Format(" {0} = {1}", "IssuedBy", issuerDistinguishedName)); foreach (var cert in collection) { Trace.WriteLine(string.Format(" {0} = {1}", "CN", cert.SubjectName.Name)); Trace.WriteLine(string.Format(" {0} = {1}", "Thumbpint", cert.Thumbprint)); } store.RemoveRange(collection); } finally { cache.Clear(); if (store != null) { store.Close(); } } } }
/// <summary> /// Delete certs that match the provided issuer. Used for cleaning up test certs. /// </summary> /// <param name="matcher"></param> internal static void DeleteCertsByIssuer(string issuerName) { X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); // Get a collection of our certs. var toRemove = new X509Certificate2Collection(); foreach (var c in store.Certificates) { var issuer = c.IssuerName.Name; if (issuer.Contains(issuerName)) { toRemove.Add(c); } } store.RemoveRange(toRemove); store.Close(); }
public bool DeleteCerts(string subjectName, StoreName name = StoreName.My, StoreLocation location = StoreLocation.CurrentUser) { bool isCompleted = false; X509Store store = new X509Store(name, location); try { store.Open(OpenFlags.ReadWrite); X509Certificate2Collection certsToRemove = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false); if (certsToRemove != null && certsToRemove.Count > 0) { store.RemoveRange(certsToRemove); isCompleted = true; } } catch (Exception e) { Console.WriteLine(e.Message); } finally { store.Close(); } return(isCompleted); }
public bool ClearCertificateCache(bool bRemoveRoot) { bool flag = true; try { X509Certificate2Collection certificates; this.oRWLock.AcquireWriterLock(-1); this.certServerCache.Clear(); this.certRoot = null; string sFullSubject = string.Format("CN={0}{1}", sMakeCertRootCN, sMakeCertSubjectO); if (bRemoveRoot) { certificates = FindCertsBySubject(StoreName.Root, StoreLocation.CurrentUser, sFullSubject); if (certificates.Count > 0) { X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); try { store.RemoveRange(certificates); } catch { flag = false; } store.Close(); } } certificates = FindCertsByIssuer(StoreName.My, sFullSubject); if (certificates.Count <= 0) { return(flag); } if (!bRemoveRoot) { X509Certificate2 rootCertificate = this.GetRootCertificate(); if (rootCertificate != null) { certificates.Remove(rootCertificate); if (certificates.Count < 1) { return(true); } } } X509Store store2 = new X509Store(StoreName.My, StoreLocation.CurrentUser); store2.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); try { store2.RemoveRange(certificates); } catch { flag = false; } store2.Close(); } finally { this.oRWLock.ReleaseWriterLock(); } return(flag); }