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


C# X509Store.Close方法代码示例

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


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

示例1: 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

示例2: Main

        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();
        }
开发者ID:lsgxeva,项目名称:MIEngine,代码行数:55,代码来源:CertTool.cs

示例3: 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

示例4: GetCertificate

        static X509Certificate2 GetCertificate(string certFindValue)
        {
            StoreLocation[] locations = new StoreLocation[] { StoreLocation.LocalMachine, StoreLocation.CurrentUser };
            foreach (StoreLocation location in locations)
            {
                X509Store store = new X509Store(StoreName.My, location);
                store.Open(OpenFlags.OpenExistingOnly);

                X509Certificate2Collection collection = store.Certificates.Find(
                    X509FindType.FindBySubjectName,
                    certFindValue,
                    false);

                if (collection.Count == 0)
                {
                    collection = store.Certificates.Find(
                        X509FindType.FindByThumbprint,
                        certFindValue,
                        false);
                }

                store.Close();

                if (collection.Count > 0)
                {
                    return collection[0];
                }
            }

            throw new ArgumentException("No certificate can be found using the find value " + certFindValue);
        }
开发者ID:rajeshganesh,项目名称:amqpnetlite,代码行数:31,代码来源:Program.cs

示例5: Initialize

        internal static X509Certificate Initialize(ICertificateConfig cerConfig)
        {
            if (!string.IsNullOrEmpty(cerConfig.FilePath))
            {
                //To keep compatible with website hosting
                string filePath;

                if (Path.IsPathRooted(cerConfig.FilePath))
                    filePath = cerConfig.FilePath;
                else
                {
                    filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cerConfig.FilePath);
                }

                return new X509Certificate2(filePath, cerConfig.Password);
            }
            else
            {
                var storeName = cerConfig.StoreName;
                if (string.IsNullOrEmpty(storeName))
                    storeName = "Root";

                var store = new X509Store(storeName);

                store.Open(OpenFlags.ReadOnly);

                var cert = store.Certificates.OfType<X509Certificate2>().Where(c =>
                    c.Thumbprint.Equals(cerConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                store.Close();

                return cert;
            }
        }
开发者ID:xxjeng,项目名称:nuxleus,代码行数:34,代码来源:CertificateManager.cs

示例6: CertificateFromFriendlyName

        public static X509Certificate2 CertificateFromFriendlyName(StoreName name, StoreLocation location, string friendlyName)
        {
            X509Store store = null;

            try
            {
                store = new X509Store(name, location);
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection foundCertificates = store.Certificates.Find(X509FindType.FindByIssuerName, "DO_NOT_TRUST_WcfBridgeRootCA", false);
                foreach (X509Certificate2 cert in foundCertificates)
                {
                    if (cert.FriendlyName == friendlyName)
                    {
                        return cert;
                    }
                }
                return null;
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }
        }
开发者ID:yxbdali,项目名称:wcf,代码行数:27,代码来源:TestHost.cs

示例7: GetCertificate

 /// <summary>
 /// Gets a X509 specific certificate from windows store withoit asking the user.
 /// </summary>
 /// <returns></returns>
 public static X509Certificate2 GetCertificate(StoreLocation location, string subjectName)
 {
     X509Certificate2 cert = null;
     var store = new X509Store(StoreName.My, location);
     store.Open(OpenFlags.ReadOnly);
     try
     {
         X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName,
                                            false);
         if (certs.Count == 1)
         {
             cert = certs[0];
         }
         else
         {
             cert = null;
         }
     }
     finally
     {
         if (store != null)
         {
             store.Close();
         }
     }
     return cert;
 }
开发者ID:rag2111,项目名称:Hexa.Core,代码行数:31,代码来源:CertificateHelper.cs

示例8: CertificadoDigital

        public CertificadoDigital()
        {
            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

            var collection = store.Certificates;
            var fcollection = collection.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
            var scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificados válidos:", "Selecione o certificado que deseja usar",
                X509SelectionFlag.SingleSelection);

            if (scollection.Count == 0)
            {
                throw new Exception("Nenhum certificado foi selecionado!");
            }

            foreach (var x509 in scollection)
            {
                try
                {
                    Serial = x509.SerialNumber;
                    Validade = Convert.ToDateTime(x509.GetExpirationDateString());

                    x509.Reset();
                }
                catch (CryptographicException)
                {
                    Console.WriteLine("Não foi possível obter as informações do certificado selecionado!");
                }
            }
            store.Close();
        }
开发者ID:riguelbf,项目名称:Zeus.Net.NFe.NFCe,代码行数:31,代码来源:CertificadoDigital.cs

示例9: 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

示例10: GetCertificateNames

        public static string[] GetCertificateNames()
        {
            List<string> certNames = new List<string>();
            X509Store store = null;
            try
            {
                store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly);
                if (store.StoreHandle != IntPtr.Zero)
                {
                    foreach (var item in store.Certificates)
                    {
                        certNames.Add(item.Subject);
                        item.Reset();
                    }
                }

                return certNames.ToArray();
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Can't open cert store locally - make sure you have permissions", ex);
            }
            finally
            {
                if (store != null) store.Close();
            }
        }
开发者ID:cicorias,项目名称:federationmetadatagenerator,代码行数:28,代码来源:CertificateHelper.cs

示例11: Run

        public void Run()
        {
            //get certificate
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            var certs = store.Certificates.Find(X509FindType.FindByThumbprint, "453990941c1cf508fb02196b474059c3c80a3678", false);
            store.Close();
            var cert = certs[0];

            //encrypt with certificates public key
            var rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;
            byte[] valueBytes = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
            byte[] encBytes = rsa.Encrypt(valueBytes, true);

            //decrypt with certificates private key
            var rsa2 = (RSACryptoServiceProvider)cert.PrivateKey;
            var unencrypted = rsa2.Decrypt(encBytes, true);
            //Console.WriteLine(Encoding.UTF8.GetString(unencrypted));


            var originalEncryptedKey =
                "KjTapgZ3NMSy8Yu5+f3guhUFmtSnPjMyYbltZ9xaFQurygU/JvX50Kty3Jkgpv0nkl9SRKlivUuai3RKVGj8DLh4Mm4ntswEB2soJ/ikWIQQXeVMABKWou8vFa+OLBFwBmkD1jURV9BzlG354Zn8qqUurw5Vh2SQP3aYLK9823ZAZXjtYOOYDB6pebiexZ9UpinmVKmgVEywxMR90272DZpPTeYYDWmMRNbiiU1C8WEHa+NNGPwjuWv5sWwLL1OHkVqoi3KSI73LIx/zw9lDDkaCkne7LcSUPN0m2tsdSrQCS9uQs5B4ti0KozJfFb+OSz6Vy3013KH+vmkXsbWL8g==";
            var decryptedOriginalKey = rsa2.Decrypt(Encoding.UTF8.GetBytes(originalEncryptedKey), true);
            Console.WriteLine("Original decrypted key: " + Convert.ToBase64String(decryptedOriginalKey));
            // This decryptedOriginalKey can then be encrypted with the new certificate to get a new Encrypted key, IV remains the same as the old one
            
            // Create new IV and Key from the certificate
            var aes = new AesManaged();
            var iv = Convert.ToBase64String(aes.IV);
            Console.WriteLine("IV: " + iv);
            var key = Convert.ToBase64String(aes.Key);
            var encryptedKey = rsa.Encrypt(Encoding.UTF8.GetBytes(key), true);
            Console.WriteLine("Encrypted Key: " + Convert.ToBase64String(encryptedKey));
        }
开发者ID:tomasking,项目名称:CryptographyDemo,代码行数:34,代码来源:FromCertificates.cs

示例12: GetCertificate

        public static X509Certificate2 GetCertificate()
        {
            var storeLocationString =  ConfigurationManager.AppSettings["storeLocation"];
            StoreLocation storeLocation;
            if (! Enum.TryParse(storeLocationString, out storeLocation))
            {
                throw new ArgumentException("Invalid store location.");
            }
            var storeName = ConfigurationManager.AppSettings["storeName"];
            var thumbprint = ConfigurationManager.AppSettings["thumbprint"];

            var store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadOnly);

            try
            {
                var certificate = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                if (certificate.Count == 0)
                {
                    throw new Exception("No certificate found.");
                }
                return certificate[0];
            }
            finally
            {
                store.Close();
            }
        }
开发者ID:bkydcmpr,项目名称:reece-example-code,代码行数:28,代码来源:CertificateFactory.cs

示例13: 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

示例14: Find

        /// <summary>
        /// Checks for the certificate in the certificate store.  Loads it from a resource if it does not exist.
        /// </summary>
        public static X509Certificate2 Find(StoreName storeName, StoreLocation storeLocation, string subjectName)
        {
            X509Certificate2 certificate = null;

            // look for the the private key in the personal store.
            X509Store store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadWrite);

            try
            {
                X509Certificate2Collection hits = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false);

                if (hits.Count == 0)
                {
                    return null;
                }

                certificate = hits[0];
            }
            finally
            {
                store.Close();
            }

            return certificate;
        }
开发者ID:yuriik83,项目名称:UA-.NET,代码行数:29,代码来源:SecurityUtils.cs

示例15: FindCertificateBy

        public static X509Certificate2 FindCertificateBy(string thumbprint, StoreName storeName, StoreLocation storeLocation, PhysicalServer server, DeploymentResult result)
        {
            if (string.IsNullOrEmpty(thumbprint)) return null;

            var certstore = new X509Store(storeName, storeLocation);

            try
            {
                certstore.Open(OpenFlags.ReadOnly);

                thumbprint = thumbprint.Trim();
                thumbprint = thumbprint.Replace(" ", "");

                foreach (var cert in certstore.Certificates)
                {
                    if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return cert;
                    }
                }

                result.AddError("Could not find a certificate with thumbprint '{0}' on '{1}'".FormatWith(thumbprint, server.Name));
                return null;
            }
            finally
            {
                certstore.Close();
            }
        }
开发者ID:Allon-Guralnek,项目名称:dropkick,代码行数:29,代码来源:BaseSecurityCertificatePermissionsTask.cs


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