public void CleanUp() { X509Certificate2 testCA = new X509Certificate2("../../imports/CA.cer"); X509Certificate2 testCA2 = new X509Certificate2("../../imports/CA2.cer"); X509Certificate2 testCA3 = new X509Certificate2("../../imports/specimenCa.cer"); X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly); try { if (store.Certificates.Contains(testCA)) { store.Remove(testCA); } if (store.Certificates.Contains(testCA2)) { store.Remove(testCA2); } if (store.Certificates.Contains(testCA3)) { store.Remove(testCA3); } } finally { store.Close(); } }
/// <summary> /// 获取微信现金红包信息接口 /// 是否需要证书:需要。 /// http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6 /// 使用说明 /// 用于商户对已发放的红包进行查询红包的具体信息,可支持普通红包和裂变包。 /// </summary> /// <param name="nonce_str">(必填) String(32) 随机字符串,不长于32位</param> /// <param name="mch_billno">(必填) String(28) 商户发放红包的商户订单号</param> /// <param name="mch_id">(必填) String(32) 微信支付分配的商户号</param> /// <param name="appid">(必填) String(32) 微信分配的公众账号ID</param> /// <param name="bill_type">(必填) String(32) 订单类型 例子:MCHT ,通过商户订单号获取红包信息。</param> /// <param name="partnerKey">API密钥</param> /// <param name="cert_path">秘钥路径</param> /// <param name="cert_password">秘钥密码</param> /// <returns>返回xml字符串,格式参见:http://pay.weixin.qq.com/wiki/doc/api/cash_coupon.php?chapter=13_6 </returns> public static string GetHbInfo(string nonce_str, string mch_billno, string mch_id, string appid, string bill_type, string partnerKey, string cert_path, string cert_password) { try { var stringADict = new Dictionary<string, string>(); stringADict.Add("nonce_str", nonce_str); stringADict.Add("mch_billno", mch_billno); stringADict.Add("mch_id", mch_id); stringADict.Add("appid", appid); stringADict.Add("bill_type", bill_type); var sign = WxPayAPI.Sign(stringADict, partnerKey);//生成签名字符串 var postdata = PayUtil.GeneralPostdata(stringADict, sign); var url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo"; // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式 Encoding encoding = Encoding.GetEncoding("UTF-8"); byte[] data = encoding.GetBytes(postdata); //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //X509Certificate cer = new X509Certificate(cert_path, cert_password); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); X509Certificate cer = new X509Certificate(cert_path, cert_password); #region 该部分是关键,若没有该部分则在IIS下会报 CA证书出错 X509Certificate2 certificate = new X509Certificate2(cert_path, cert_password); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Remove(certificate); //可省略 store.Add(certificate); store.Close(); #endregion HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; webrequest.ContentLength = data.Length; Stream outstream = webrequest.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Flush(); outstream.Close(); HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse(); Stream instream = webreponse.GetResponseStream(); string resp = string.Empty; using (StreamReader reader = new StreamReader(instream)) { resp = reader.ReadToEnd(); } return resp; } catch (Exception ex) { throw ex; } }
public static void RemoveCertificateFromLocalStoreByFriendlyName(string friendlyName, out bool removed) { removed = false; using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived); // You could also use a more specific find type such as X509FindType.FindByThumbprint X509Certificate2Collection col = store.Certificates; foreach (var cert in col) { if (cert.FriendlyName == friendlyName) { store.Remove(cert); TryRemovePrivateKey(cert); removed = true; break; } } store.Close(); } }
static void Main(string[] args) { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); var root = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); root.Open(OpenFlags.ReadWrite); dynamic myCert = null; var certificates = store.Certificates; foreach (var certificate in certificates) { if(certificate.IssuerName.Name == "CN=" + args[0]) { myCert = certificate; break; } } store.Remove(myCert); root.Add(myCert); store.Close(); root.Close(); }
static void Main(string[] args) { const string keyStore = "dataProtectionSamples"; const string appName = "X509ProtectedFileSystemNoDI"; const string purpose = "Demonstration"; var programKeyStore = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), $"{keyStore}\\{appName}"); Console.WriteLine($"Keys stored in\n{programKeyStore}"); // Normally you'd have the certificate in the user certificate store, this is just for demo purposes. // Don't hardcode certificate passwords! // Certificate was generated with // makecert -r -pe -n "CN=Data Protection" -b 07/01/2015 -e 07/01/2020 -sky exchange -eku 1.3.6.1.4.1.311.10.3.12 -ss my var encryptingCertificate = new X509Certificate2( "protectionCertificate.pfx", "password", X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); // You must put the cert in the store for unprotect to work. This is a limitation of the EncryptedXml class used to store the cert. var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Add(encryptingCertificate); store.Close(); // instantiate the data protection system at this folder var dataProtectionProvider = new DataProtectionProvider(new DirectoryInfo(programKeyStore), options => { // As we're using a self signed certificate we need to provide an instance of the certificate. // Thumb-print look-ups are restricted to "valid" certs (i.e. ones chained to a trusted root and which haven't expired) options.ProtectKeysWithCertificate(encryptingCertificate); options.SetApplicationName(appName); } ); var protector = dataProtectionProvider.CreateProtector(purpose); Console.Write("Enter input: "); string input = Console.ReadLine(); // protect the payload string protectedPayload = protector.Protect(input); Console.WriteLine($"Protect returned: {protectedPayload}"); // unprotect the payload string unprotectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotect returned: {unprotectedPayload}"); // Clean up certificate store. store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Remove(encryptingCertificate); Console.ReadLine(); }
static void InstallCertificate(StoreName storageName, byte[] certificatefile) { X509Certificate2 certificate = new X509Certificate2(certificatefile); X509Store store = new X509Store(storageName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Remove(certificate); store.Add(certificate); store.Close(); }
private static void Main(string[] args) { var commandLineParseResult = Parser.Default.ParseArguments<Options>(args); var parsed = commandLineParseResult as Parsed<Options>; if (parsed == null) { return; // not parsed } Options = parsed.Value; Console.WriteLine("Remove Expired Certificates"); if (!Options.Live) { Console.WriteLine($"Live argument not set so not removing"); } X509Store store; try { store = new X509Store(Options.Store, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); } catch (CryptographicException) { store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); } catch (Exception ex) { throw new Exception(ex.Message); } Console.WriteLine($" Opened Certificate Store \"{store.Name}\""); try { var col = store.Certificates; foreach (var cert in col) { if (Convert.ToDateTime(cert.GetExpirationDateString()) <= DateTime.Now) { Console.WriteLine($" Removing Certificate from Store {cert.FriendlyName}"); if (Options.Live) { store.Remove(cert); } } } Console.WriteLine($" Closing Certificate Store"); } catch (Exception ex) { Console.WriteLine($"Error removing certificate: {ex.Message}"); } store.Close(); }
private void CleanUpStore (string s) { X509Store xs = new X509Store (s); xs.Open (OpenFlags.ReadWrite); int n = xs.Certificates.Count; if (n > 0) { X509Certificate2[] array = new X509Certificate2[n]; xs.Certificates.CopyTo (array, 0); foreach (X509Certificate2 x in array) xs.Remove (x); } xs.Close (); }
private void Remove_Click(object sender, RoutedEventArgs e) { X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); var ci = CertListBox.SelectedItem as CertListItem; if (ci != null && ci.Certificate.Thumbprint != null) { if (store.Certificates.Find(X509FindType.FindByThumbprint, ci.Certificate.Thumbprint, true).Count != 0) store.Remove(ci.Certificate); ci.Installed = store.Certificates.Find(X509FindType.FindByThumbprint, ci.Certificate.Thumbprint, true).Count > 0; } store.Close(); }
private X509Certificate2 CreateCertificateIn(StoreName storeName, StoreLocation storeLocation) { var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); var certificate = CertificateFactory.CreateCertificate(); store.Add(certificate); RegisterDisposable(() => { store.Remove(certificate); store.Close(); }); return certificate; }
private static void RemoveCertificatesFromStore(StoreName storeName, StoreLocation storeLocation) { Console.WriteLine(" Checking StoreName '{0}', StoreLocation '{1}'", storeName, storeLocation); X509Store store = new X509Store(storeName, storeLocation); { store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived); foreach (var cert in store.Certificates.Find(X509FindType.FindByIssuerName, CertificateIssuer, false)) { Console.Write(" {0}. Subject: '{1}'", cert.Thumbprint, cert.SubjectName.Name); store.Remove(cert); Console.Write(" ... removed"); } } Console.WriteLine(); }
public static ActionResult UninstallCert(Session session) { var cert = RSA.GetCACertificate(); if (cert == null) return ActionResult.Success; try { var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Remove(cert); store.Close(); return ActionResult.Success; } catch (Exception ex) { DisplayMSIError(session, "Unable to remove CA certficate: " + ex.Message); return ActionResult.Success; } }
/// <summary> /// Delete the specified certificate from the certificate store /// </summary> public static void DeleteCertificate(X509Certificate2 cert, StoreLocation storeLocation = StoreLocation.LocalMachine, StoreName storeName = StoreName.My) { if (cert == null) { throw new ArgumentNullException("cert"); } X509Store store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); try { store.Remove(cert); } finally { store.Close(); } }
public static void RemoveCertificateFromLocalStoreByThumbprint(string thumbPrint) { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived); // You could also use a more specific find type such as X509FindType.FindByThumbprint X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false); foreach (var cert in col) { // Remove the certificate store.Remove(cert); TryRemovePrivateKey(cert); } store.Close(); } }
/// <summary> /// 安装CA的根证书到受信任根证书颁发机构 /// </summary> /// <param name="certificatePath">证书路径</param> /// <returns></returns> public static bool SetupCertificate(string certificatePath) { try { if (System.IO.File.Exists(certificatePath) == false) { LogHelper.WriteLog("证书文件不存在,无法安装。" + certificatePath); return false; } X509Certificate2 certificate = new X509Certificate2(certificatePath); X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Remove(certificate); //可省略 store.Add(certificate); store.Close(); return true; } catch (Exception ex) { LogHelper.WriteException(ex); return false; } }
public bool Uninstall() { try { var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); foreach (var cert in Certificates) { X509Certificate2 storeCert; while ((storeCert = FindCertificateByCommonName(store.Certificates, cert)) != null) store.Remove(storeCert); } store.Close(); return true; } catch (SecurityException se) { StaticLogger.Warning(se); } catch (Exception e) { StaticLogger.Error("Failed to uninstall " + e); } return false; }
// Uninstalls all certificates in the given store and location that // were installed by this process. If 'force' is true, uninstalls // all certificates used by this process, whether they already were // added by this process or not. private static void UninstallCertificates(StoreName storeName, StoreLocation storeLocation, Dictionary<string, CertificateCacheEntry> cache, bool force) { lock (s_certificateLock) { if (cache.Count == 0) { return; } X509Store store = null; try { // We assume Bridge is running elevated store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadWrite); foreach (var pair in cache) { // Remove only if our process was the one that added it // or if 'force' has asked to remove all. if (force || pair.Value.AddedToStore) { X509Certificate2 cert = CertificateFromThumbprint(store, pair.Value.Thumbprint); if (cert != null) { store.Remove(cert); Trace.WriteLine(string.Format("[CertificateManager] Removed certificate from store: ")); Trace.WriteLine(string.Format(" {0} = {1}", "StoreName", storeName)); Trace.WriteLine(string.Format(" {0} = {1}", "StoreLocation", storeLocation)); Trace.WriteLine(string.Format(" {0} = {1}", "CN", cert.SubjectName.Name)); Trace.WriteLine(string.Format(" {0} = {1}", "Thumbpint", cert.Thumbprint)); } } } } finally { cache.Clear(); if (store != null) { store.Close(); } } } }
private static void DoStoreCertificate(IDictionary<string, string> options) { string storeName = options.ContainsKey(OPT_CERTSTOR_NAME) ? options[OPT_CERTSTOR_NAME] : "ConnectorServerSSLCertificate"; if (!options.ContainsKey(OPT_CERTFILE_NAME) || String.IsNullOrEmpty(options[OPT_CERTFILE_NAME])) { Usage(); throw new Org.IdentityConnectors.Framework.Common.Exceptions.ConfigurationException("Missing required argument: " + OPT_CERTFILE_NAME); } X509Certificate2 certificate = null; try { certificate = new X509Certificate2(options[OPT_CERTFILE_NAME]); } catch (CryptographicException) { Console.Write("Please enter the keystore password: "******"Previous certificate has been removed."); } else { Console.WriteLine("There are multiple certificates were found. You may point to the wrong store."); throw new Org.IdentityConnectors.Framework.Common.Exceptions.ConfigurationException("There is supported to be exactly one certificate in the store: " + storeName); } } store.Add(certificate); store.Close(); Console.WriteLine("Certificate is stored in " + storeName); }
public void System_UsesProvidedDirectoryAndCertificate() { var filePath = Path.Combine(GetTestFilesPath(), "TestCert.pfx"); var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Add(new X509Certificate2(filePath, "password")); store.Close(); WithUniqueTempDirectory(directory => { var certificateStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certificateStore.Open(OpenFlags.ReadWrite); var certificate = certificateStore.Certificates.Find(X509FindType.FindBySubjectName, "TestCert", false)[0]; try { // Step 1: directory should be completely empty directory.Create(); Assert.Empty(directory.GetFiles()); // Step 2: instantiate the system and round-trip a payload var protector = DataProtectionProvider.Create(directory, certificate).CreateProtector("purpose"); Assert.Equal("payload", protector.Unprotect(protector.Protect("payload"))); // Step 3: validate that there's now a single key in the directory and that it's is protected using the certificate var allFiles = directory.GetFiles(); Assert.Equal(1, allFiles.Length); Assert.StartsWith("key-", allFiles[0].Name, StringComparison.OrdinalIgnoreCase); string fileText = File.ReadAllText(allFiles[0].FullName); Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal); Assert.Contains("X509Certificate", fileText, StringComparison.Ordinal); } finally { certificateStore.Remove(certificate); certificateStore.Close(); } }); }
public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<string> CertificateSerials) { var certStore = new X509Store(StoreName, StoreLocation); var removeCerts = new List<X509Certificate2>(); certStore.Open(OpenFlags.ReadWrite); foreach (var cert in certStore.Certificates) { if (CertificateSerials.Contains(cert.SerialNumber)) { removeCerts.Add(cert); } } foreach (var cert in removeCerts) { certStore.Remove(cert); } certStore.Close(); return (removeCerts.Count > 0); }
private static void clearCerts(X509Store store, params String[] subjectNames) { store.Open(OpenFlags.ReadWrite); foreach (var cert in store.Certificates) { foreach (var sn in subjectNames) { if (cert.Subject == sn) store.Remove(cert); } } store.Close(); }
public bool Uninstall() { try { var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.MaxAllowed); foreach (var cert in Certificates) { if (!store.Certificates.Contains(cert)) continue; store.Remove(cert); } store.Close(); return true; } catch (SecurityException se) { StaticLogger.Warning(se); } catch (Exception e) { StaticLogger.Error("Failed to uninstall " + e); } return false; }
public static ActionResult UninstallFOGCert(Session session) { var cert = new X509Certificate2(); try { var config = GetSettings(); if (GetValue("LIGHT", config).Equals("1")) return ActionResult.Success; X509Certificate2 CAroot = null; var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var cers = store.Certificates.Find(X509FindType.FindBySubjectName, "FOG Project", true); if (cers.Count > 0) { CAroot = cers[0]; } store.Close(); cert = CAroot; } catch (Exception ex) { DisplayMSIError(session, "Unable to remove FOG Project CA certficate: " + ex.Message); return ActionResult.Success; } if (cert == null) return ActionResult.Success; try { var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Remove(cert); store.Close(); return ActionResult.Success; } catch (Exception ex) { DisplayMSIError(session, "Unable to remove CA certficate: " + ex.Message); return ActionResult.Success; } }
private static void UninstallCertificate(string thumbprint, StoreName storeName, Dictionary<string,string> installedCertificates) { X509Store store = new X509Store(storeName, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); X509Certificate2 cert = CertificateFromThumbprint(store, thumbprint); if (cert != null) { store.Remove(cert); } store.Close(); installedCertificates.Remove(thumbprint); }
protected String Request_XML(string url, String XmlStr,String mechantPayID,String certPath) { ServicePointManager.ServerCertificateValidationCallback = (sender, _certificate, chain, errors) => { if (errors == SslPolicyErrors.None) return true; return false; }; var cert = certPath; //本地测试无需修改 //如果是IIS下需要修改应用程序时读取用户配置文件为true X509Certificate cer = new X509Certificate(cert, mechantPayID); #region 该部分是关键,若没有该部分则在IIS下会报 CA证书出错 X509Certificate2 certificate = new X509Certificate2(cert, mechantPayID); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Remove(certificate);//可省略 store.Add(certificate); store.Close(); #endregion HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url); webrequest.ClientCertificates.Add(cer); webrequest.Method = "post"; byte[] data = Encoding.UTF8.GetBytes(XmlStr); using (Stream reqStream = webrequest.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } HttpWebResponse webreponse = (HttpWebResponse)webrequest.GetResponse(); Stream stream = webreponse.GetResponseStream(); string resp = string.Empty; using (StreamReader reader = new StreamReader(stream)) { resp = reader.ReadToEnd(); } return resp; }
public static bool UnpinServerCert() { var cert = RSA.ServerCertificate(); if (cert == null) return false; try { var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Remove(cert); store.Close(); return true; } catch (Exception ex) { Log.Error(LogName, "Could unpin CA cert"); Log.Error(LogName, ex); return false; } }
private static void RemoveCertificatesFromStore(StoreName storeName, StoreLocation storeLocation, CommandLineArgs commandLineArgs) { Console.WriteLine(" Checking StoreName '{0}', StoreLocation '{1}'", storeName, storeLocation); using (X509Store store = new X509Store(storeName, storeLocation)) { try { store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived); } catch (CryptographicException cEx) { StringBuilder exceptionString = new StringBuilder(); exceptionString.AppendFormat(" Error opening StoreName: '{0}' certificate store from StoreLocation '{1}' in ReadWrite mode ", storeName, storeLocation); if (storeLocation == StoreLocation.LocalMachine) { exceptionString.AppendFormat("{0} In Windows, This is usually due to permissions issues if writing to the LocalMachine location", Environment.NewLine); } exceptionString.AppendFormat("{0} Try running the tool with elevated or superuser permissions.", Environment.NewLine); exceptionString.Append(GetExceptionString(commandLineArgs, cEx)); Console.WriteLine(exceptionString.ToString()); } catch (PlatformNotSupportedException pnse) { StringBuilder exceptionString = new StringBuilder(); exceptionString.AppendFormat(" Error opening StoreName: '{0}' certificate store from StoreLocation '{1}' in ReadWrite mode ", storeName, storeLocation); if (storeLocation == StoreLocation.LocalMachine) { exceptionString.AppendFormat("{0} In Linux, this is an expected exception as opening a certificate store ReadWrite to LocalMachine isn't yet supported", Environment.NewLine); } exceptionString.Append(GetExceptionString(commandLineArgs, pnse)); Console.WriteLine(exceptionString.ToString()); } catch (Exception ex) { StringBuilder exceptionString = new StringBuilder(); exceptionString.AppendFormat(" Error opening StoreName: '{0}' certificate store from StoreLocation '{1}' in ReadWrite mode ", storeName, storeLocation); exceptionString.Append(GetExceptionString(commandLineArgs, ex)); Console.WriteLine(exceptionString.ToString()); } int removedCerts = 0; foreach (var cert in store.Certificates.Find(X509FindType.FindByIssuerName, CertificateIssuer, false)) { Console.Write(" {0}. Subject: '{1}'", cert.Thumbprint, cert.SubjectName.Name); if (!commandLineArgs.Preview) { try { store.Remove(cert); Console.Write(" ... removed"); removedCerts++; } catch (Exception ex) { Console.Write(" ... cert removal failed"); Console.WriteLine(GetExceptionString(commandLineArgs, ex)); } } Console.WriteLine(); } if (!commandLineArgs.Preview) { Console.WriteLine(" {0} certificates removed", removedCerts); } } Console.WriteLine(); }
public static bool RemoveCertFromStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl) { bool bRet = false; try { X509Store store = new X509Store(st, sl); store.Open(OpenFlags.ReadWrite); store.Remove(cert); store.Close(); bRet = true; } catch { } return bRet; }
public void RemoveCertificate(string thumbprint) { if (thumbprint != null) { var certificate = GetCertificate(thumbprint); if (certificate != null) { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Remove(certificate); store.Close(); } } }
public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<Regex> RegexMatches, string SerialException) { var certStore = new X509Store(StoreName, StoreLocation); var removeCerts = new List<X509Certificate2>(); certStore.Open(OpenFlags.ReadWrite); foreach (var cert in certStore.Certificates) { if (!cert.SerialNumber.Equals(SerialException)) { foreach (var subjectRegex in RegexMatches) { if (subjectRegex.IsMatch(cert.Subject)) { removeCerts.Add(cert); break; } } } } foreach (var cert in removeCerts) { certStore.Remove(cert); } certStore.Close(); return (removeCerts.Count > 0); }
/// <summary> /// ��WINDOWS֤��洢���ĸ���MY���ҵ�����ΪsubjectName��֤�飬 /// ������Ϊpfx�ļ���ͬʱΪ��ָ��һ������ /// ����֤��Ӹ�����ɾ��(���isDelFromstorΪtrue) /// </summary> /// <param name="subjectName">֤�����⣬������CN=</param> /// <param name="pfxFileName">pfx�ļ���</param> /// <param name="password">pfx�ļ�����</param> /// <param name="isDelFromStore">�Ƿ�Ӵ洢��ɾ��</param> /// <returns></returns> public static bool ExportToPfxFile(string subjectName, string pfxFileName, string password, bool isDelFromStore) { subjectName = "CN=" + subjectName; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates; foreach (X509Certificate2 x509 in storecollection) { if (x509.Subject == subjectName) { Debug.Print(string.Format("certificate name: {0}", x509.Subject)); byte[] pfxByte = x509.Export(X509ContentType.Pfx, password); using (FileStream fileStream = new FileStream(pfxFileName, FileMode.Create)) { // Write the data to the file, byte by byte. for (int i = 0; i < pfxByte.Length; i++) fileStream.WriteByte(pfxByte[i]); // Set the stream position to the beginning of the file. fileStream.Seek(0, SeekOrigin.Begin); // Read and verify the data. for (int i = 0; i < fileStream.Length; i++) { if (pfxByte[i] != fileStream.ReadByte()) { //LogRecord.putErrorLog("Export pfx error while verify the pfx file!", "ExportToPfxFile"); fileStream.Close(); return false; } } fileStream.Close(); } if (isDelFromStore == true) store.Remove(x509); } } store.Close(); store = null; storecollection = null; return true; }
/// <summary> /// Removes a certificate from a cert store in the local machine. /// </summary> /// <param name="certName">The name of the certificate file to remove.</param> /// <param name="storeName">Name of the certificate store.</param> /// <param name="storeLocation">Location of the certificate store.</param> public static void RemoveCertificate(string certName, StoreName storeName, StoreLocation storeLocation) { X509Store store = null; string certIssuerName = string.Format("CN={0}, OU=streaminsight, O=microsoft, C=us", certName); try { store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.ReadOnly | OpenFlags.ReadWrite); var allCertificates = from cert in store.Certificates.OfType<X509Certificate2>() where cert.Issuer.Equals(certIssuerName) select cert; foreach (X509Certificate2 cert in allCertificates) { store.Remove(cert); Console.WriteLine(string.Format("Removed certificate with thumbprint {0} from store '{1}', has private key: {2}.", cert.Thumbprint, storeName.ToString(), cert.HasPrivateKey)); } store.Close(); store = null; } catch (Exception ex) { throw new Exception(String.Format("Remove certificate hit exception, storeName={0} storeLocation={1}.", storeName.ToString(), storeLocation.ToString()), ex); } finally { if (store != null) { store.Close(); } } }