当前位置: 首页>>代码示例>>C#>>正文


C# X509Store.Add方法代码示例

本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Store.Add方法的典型用法代码示例。如果您正苦于以下问题:C# X509Store.Add方法的具体用法?C# X509Store.Add怎么用?C# X509Store.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Cryptography.X509Certificates.X509Store的用法示例。


在下文中一共展示了X509Store.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AddCertificate

        private void AddCertificate()
        {
            var store = new X509Store(_storeName, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(new X509Certificate2("RootTrustedCA.cer"));


            var certificate = new X509Certificate2("Server.cer");
            store.Add(certificate);
            _certificateThumbprint = certificate.Thumbprint;

            _certificateConfiguration = new CertificateConfiguration
            {
                FindBy = X509FindType.FindByThumbprint,
                StoreLocation = StoreLocation.LocalMachine,
                StoreName = _storeName,
                Value = _certificateThumbprint
            };

            try
            {
                // Required for server to successfully pick up the certificate
                _certificateConfiguration.BindCertificateToPort("6661");
                _certificateConfiguration.BindCertificateToPort("6671");
                _certificateConfiguration.BindCertificateToPort("6681");
            }
            catch
            {
            }
            store.Close();
        }
开发者ID:punitganshani,项目名称:KonfDB,代码行数:31,代码来源:ServiceTest.cs

示例2: SetUp

        public void SetUp()
        {
            X509Certificate2 testCA = new X509Certificate2("../../imports/CA.cer");
            X509Certificate2 testCA2 = new X509Certificate2("../../imports/CA2.cer");
            X509Certificate2 testCA3 = new X509Certificate2("../../imports/specimenCa.cer");

            X509Certificate2 testIntCA = new X509Certificate2("../../imports/specimenCitizenCa.cer");

            X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);
            try
            {
                if (!store.Certificates.Contains(testCA))
                {
                    store.Add(testCA);
                }
                if (!store.Certificates.Contains(testCA2))
                {
                    store.Add(testCA2);
                }
                if (!store.Certificates.Contains(testCA3))
                {
                    store.Add(testCA3);
                }
            }
            finally
            {
                store.Close();
            }
        }
开发者ID:svn2github,项目名称:etee,代码行数:30,代码来源:Config.cs

示例3: Main

        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();
        }
开发者ID:girish66,项目名称:Oak,代码行数:25,代码来源:move_cert.cs

示例4: Execute

        public void Execute(object parameter)
        {
            var pfx = CertificateManager.GeneratePfx(CertificateName, CertificatePassword);
            var certificate = CertificateManager.GetCertificateForBytes(pfx.GetBytes(), CertificatePassword);

            File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), pfx.GetBytes());
            File.WriteAllBytes(Path.Combine(AppHelper.CachePath, "AzureAutomation.cer"), certificate);

            var collection = new X509Certificate2Collection();
            collection.Import(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"), CertificatePassword, X509KeyStorageFlags.PersistKeySet);

            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);

            // Store the certificate
            foreach (var cert in collection)
                store.Add(cert);

            store.Close();

            // Delete the certificate that contains the private key - this is already imported into the cert store
            File.Delete(Path.Combine(AppHelper.CachePath, "AzureAutomation.pfx"));

            MessageBox.Show("The certificate has been generated. Please refresh the certificates list.", "Certificate", MessageBoxButton.OK);

            // Open the folder containing the certificate
            Process.Start("explorer.exe", AppHelper.CachePath);
        }
开发者ID:peterschen,项目名称:SMAStudio,代码行数:28,代码来源:GenerateCertificateCommand.cs

示例5: InstallCertificate

        private void InstallCertificate(StoreName storeName, StoreLocation storeLocation)
        {
            Trace.TraceInformation("Creating store object for '{1}', '{0}'.", storeName, storeLocation);
            var store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadWrite);
            try
            {
                X509Certificate2Collection result = store.Certificates.Find(
                    X509FindType.FindByThumbprint, _cert.Thumbprint, false);

                if (result.Count > 0)
                {
                    Trace.TraceWarning("Certificate with thumbprint '{0}', name '{1}' already in store.",
                        _cert.Thumbprint, _cert.Subject);
                }
                else
                {
                    store.Add(_cert);
                    Trace.TraceInformation("Certificate successfully added to the store.");
                }
            }
            finally
            {
                store.Close();
            }
        }
开发者ID:Kstal,项目名称:Microsoft.Owin,代码行数:26,代码来源:CertificateInstaller.cs

示例6: RegisterCertificate

        /// <summary>
        /// Install a certificate to local machine store
        /// </summary>
        /// <param name="certificateFilePath"></param>
        /// <returns>Certificate added to the store.</returns>
        public static X509Certificate2 RegisterCertificate(string certificateFilePath)
        {
            // STEP 1: install the certificate to Local Machine store
            if (!File.Exists(certificateFilePath))
            {
                throw new ArgumentException("Certificate file doesn't exist.");
            }

            var certificate = new X509Certificate2(
                certificateFilePath, "1234", X509KeyStorageFlags.MachineKeySet);

            var store = new X509Store(StoreLocation.LocalMachine);

            try
            {
                store.Open(OpenFlags.ReadWrite);
                var results = store.Certificates.Find(X509FindType.FindBySerialNumber, certificate.SerialNumber, true);
                if (results.Count == 0)
                {
                    store.Add(certificate);
                }
            }
            finally
            {
                store.Close();
            }

            return certificate;
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:34,代码来源:SecurityHelper.cs

示例7: InstallCertificate

		/// <summary>
		/// Returns null if successful, or an error string if it failed
		/// </summary>
		public static string InstallCertificate(string CertificateFilename, string PrivateKeyFilename)
		{
			try
			{
				// Load the certificate
				string CertificatePassword = "";
				X509Certificate2 Cert = new X509Certificate2(CertificateFilename, CertificatePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
				if (!Cert.HasPrivateKey)
				{
					return "Error: Certificate does not include a private key and cannot be used to code sign";
				}

				// Add the certificate to the store
				X509Store Store = new X509Store();
				Store.Open(OpenFlags.ReadWrite);
				Store.Add(Cert);
				Store.Close();
			}
			catch (Exception ex)
			{
				string ErrorMsg = String.Format("Failed to load or install certificate with error '{0}'", ex.Message);
				Program.Error(ErrorMsg);
				return ErrorMsg;
			}

			return null;
		}
开发者ID:ErwinT6,项目名称:T6Engine,代码行数:30,代码来源:CodeSigning.cs

示例8: AddCertToStore

 private static void AddCertToStore(X509Certificate2 certificate, X509Store store)
 {
     store.Open(OpenFlags.ReadWrite);
     store.Add(certificate);
     store.Close();
     Console.WriteLine("Certificate installed in store.");
 }
开发者ID:kjelliverb,项目名称:ConDep,代码行数:7,代码来源:CertificateInstaller.cs

示例9: addcertificates

        static void addcertificates(string installdir)
        {
            if (File.Exists(installdir + "\\eapcitrix.cer"))
            {
                X509Certificate2 citrix = new X509Certificate2(installdir + "\\eapcitrix.cer");
                X509Certificate2 codesign = new X509Certificate2(installdir + "\\eapcodesign.cer");
                X509Certificate2 root = new X509Certificate2(installdir + "\\eaproot.cer");
                X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(citrix);
                store.Close();
                store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(codesign);
                store.Close();
                store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(root);
                store.Close();
                try
                {
                    EventLog.WriteEntry(esource, "InstallGui Install Helpers Added");
                }
                catch { }
            }
            else
            {
                try
                {
                    EventLog.WriteEntry(esource, "InstallGui Install Helpers Not Needed");
                }
                catch { }

            }
        }
开发者ID:rkuschel,项目名称:win-installer,代码行数:35,代码来源:Program.cs

示例10: AddCertificate

        /// <summary>
        /// Adds a certificate to a cert store in the local machine.
        /// </summary>
        /// <param name="certificate">The file path to find the certificate file.</param>
        /// <param name="storeName">Name of the certificate store.</param>
        /// <param name="storeLocation">Location of the certificate store.</param>
        public static void AddCertificate(X509Certificate2 certificate, StoreName storeName, StoreLocation storeLocation)
        {
            X509Store store = null;

            try
            {
                store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadOnly | OpenFlags.ReadWrite);

                var certificates = from cert in store.Certificates.OfType<X509Certificate2>()
                                   where cert.Thumbprint == certificate.Thumbprint
                                   select cert;

                if (certificates.FirstOrDefault() == null)
                {
                    store.Add(certificate);
                    Console.WriteLine(string.Format("Added certificate with thumbprint {0} to store '{1}', has private key: {2}.", certificate.Thumbprint, storeName.ToString(), certificate.HasPrivateKey));

                    store.Close();
                    store = null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("AddCert exception storeName={0} storeLocation={1}", storeName.ToString(), storeLocation.ToString()), ex);
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }
        }
开发者ID:hendryluk,项目名称:twitterbigdata,代码行数:40,代码来源:CertificateHelper.cs

示例11: AddToStoreIfNeeded

        // Adds the given certificate to the given store unless it is
        // already present.  Returns 'true' if the certificate was added.
        private static bool AddToStoreIfNeeded(StoreName storeName,
                                               StoreLocation storeLocation,
                                               X509Certificate2 certificate)
        {
            X509Store store = null;
            X509Certificate2 existingCert = null;
            try
            {
                store = new X509Store(storeName, storeLocation);

                // We assume Bridge is running elevated
                store.Open(OpenFlags.ReadWrite);
                existingCert = CertificateFromThumbprint(store, certificate.Thumbprint);
                if (existingCert == null)
                {
                    store.Add(certificate);
                    Trace.WriteLine(string.Format("[CertificateManager] Added certificate to store: "));
                    Trace.WriteLine(string.Format("    {0} = {1}", "StoreName", storeName));
                    Trace.WriteLine(string.Format("    {0} = {1}", "StoreLocation", storeLocation));
                    Trace.WriteLine(string.Format("    {0} = {1}", "CN", certificate.SubjectName.Name));
                    Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey", certificate.HasPrivateKey));
                    Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", certificate.Thumbprint));
                }

            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return existingCert == null;
        }
开发者ID:Richard-FF,项目名称:wcf,代码行数:37,代码来源:CertificateManager.cs

示例12: GetHbInfo

        /// <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;
            }
        }
开发者ID:Cold1986,项目名称:MZZ,代码行数:76,代码来源:WxHbPayAPI.cs

示例13: Install

        public bool Install()
        {
            try
            {
                var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.MaxAllowed);
                var names = GetCommonNames(store.Certificates);
                foreach (var cert in Certificates)
                {
                    if (names.Contains(GetCommonName(cert)))
                        continue;
                    store.Add(cert);
                }
                store.Close();

                return true;
            }
            catch (SecurityException se)
            {
                StaticLogger.Warning(se);
            }
            catch (Exception e)
            {
                StaticLogger.Error("Failed to install " + e);
            }
            return false;
        }
开发者ID:Boreeas,项目名称:LoLNotes,代码行数:27,代码来源:CertificateInstaller.cs

示例14: AddToStoreIfNeeded

        // Adds the given certificate to the given store unless it is
        // already present.  Returns 'true' if the certificate was added.
        private static bool AddToStoreIfNeeded(StoreName storeName, 
                                               StoreLocation storeLocation, 
                                               X509Certificate2 certificate)
        {
            X509Store store = null;
            X509Certificate2 existingCert = null;
            try
            {
                store = new X509Store(storeName, storeLocation);
                store.Open(OpenFlags.ReadWrite);
                existingCert = CertificateFromThumbprint(store, certificate.Thumbprint);
                if (existingCert == null)
                {
                    store.Add(certificate);
                    Console.WriteLine("Added to store '{0}', location '{1}', certificate '{2}'", 
                                       storeName, storeLocation, certificate.SubjectName.Name);
                }

            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return existingCert == null;
        }
开发者ID:dmetzgar,项目名称:wcf,代码行数:31,代码来源:CertificateManager.cs

示例15: InstallCert

        public static ActionResult InstallCert(Session session)
        {
            var cert = RSA.GetCACertificate();
            if (cert != null) return ActionResult.Success;

            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Configuration.ServerAddress = Configuration.ServerAddress.Replace("https://", "http://");
            var keyPath = string.Format("{0}ca.cert.der", tempDirectory);
            var downloaded = Communication.DownloadFile("/management/other/ca.cert.der", keyPath);
            if (!downloaded)
            {
                DisplayMSIError(session, "Failed to download CA certificate");
                return ActionResult.Failure;
            }

            try
            {
                cert = new X509Certificate2(keyPath);
                var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);

                store.Close();
                return ActionResult.Success;
            }
            catch (Exception ex)
            {
                DisplayMSIError(session, "Unable to install CA certificate: " + ex.Message);
                return ActionResult.Failure;
            }
        }
开发者ID:uw-it-cte,项目名称:fog-client,代码行数:32,代码来源:CustomAction.cs


注:本文中的System.Security.Cryptography.X509Certificates.X509Store.Add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。