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


C# X509Store.Open方法代码示例

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


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

示例1: Main

    static void Main()
    {
        try {
            X509Store store = new X509Store("MY",StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection =
                X509Certificate2UI.SelectFromCollection(
                    (X509Certificate2Collection)store.Certificates,
                    "Certificate selection",
                    "Select a certificate to obtain the container name from",
                    X509SelectionFlag.SingleSelection);

            if (collection.Count == 1) {
                X509Certificate2 x509 = collection[0] ;
                Console.WriteLine("Subject: {0}", x509.Subject) ;
                Console.WriteLine("Friendly name: {0}", x509.FriendlyName) ;
                if (x509.PrivateKey != null) {
                    ICspAsymmetricAlgorithm pkey = x509.PrivateKey
                        as ICspAsymmetricAlgorithm ;
                    Console.WriteLine("Key container name: {0}",
                        pkey.CspKeyContainerInfo.KeyContainerName);
                }
                x509.Reset();
            }
            store.Close();
        }
        catch (Exception e) {
           Console.WriteLine(e.ToString()) ;
        }
    }
开发者ID:spujadas,项目名称:tp-confiance,代码行数:30,代码来源:GetContainerNameFromCertPicker.cs

示例2: LoadCertificate

        X509Certificate2 LoadCertificate()
        {
            string thumbprint = ConfigurationManager.AppSettings["nuget:Thumbprint"];
            Thumbprint = thumbprint;

            if (string.IsNullOrWhiteSpace(thumbprint))
            {
                return null;
            }

            X509Store certStore = null;
            try
            {
                certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                certStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                if (certCollection.Count > 0)
                {
                    return certCollection[0];
                }
                return null;
            }
            finally
            {
                if (certStore != null)
                {
                    certStore.Close();
                }
            }
        }
开发者ID:jinujoseph,项目名称:NuGet.Services.Metadata,代码行数:30,代码来源:Startup.Auth.cs

示例3: FindX509Certificate

 private static X509Certificate2 FindX509Certificate(string thumbprint)
 {
     List<StoreLocation> locations = new List<StoreLocation>
     { 
         StoreLocation.CurrentUser, 
         StoreLocation.LocalMachine
     };
     foreach (var location in locations)
     {
         X509Store store = new X509Store("My", location);
         try
         {
             store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
             X509Certificate2Collection certificates = store.Certificates.Find(
                 X509FindType.FindByThumbprint, thumbprint, false);
             if (certificates.Count == 1)
             {
                 return certificates[0];
             }
         }
         finally
         {
             store.Close();
         }
     }
     throw new ArgumentException(string.Format("A Certificate with Thumbprint '{0}' could not be located.", thumbprint));
 }
开发者ID:rahulkarnthobb,项目名称:Ijepai-Poc,代码行数:27,代码来源:VMManager.cs

示例4: X509CertStoreChain

        public static void X509CertStoreChain()
        {
            X509Store store = new X509Store("My", StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            // can't guarantee there is a certificate in store
            if (store.Certificates.Count > 0)
            {
                X509Chain chain = new X509Chain();
                Assert.NotNull(chain.SafeHandle);
                Assert.Same(chain.SafeHandle, chain.SafeHandle);
                Assert.True(chain.SafeHandle.IsInvalid);

                foreach (X509Certificate2 c in store.Certificates)
                {
                    // can't guarantee success, so no Assert 
                    if (chain.Build(c))
                    {
                        foreach (X509ChainElement k in chain.ChainElements)
                        {
                            Assert.NotNull(k.Certificate.IssuerName.Name);
                        }
                    }
                }
            }
        }
开发者ID:noahfalk,项目名称:corefx,代码行数:25,代码来源:CertTests.cs

示例5: OpenNotExistant

 public static void OpenNotExistant()
 {
     using (X509Store store = new X509Store(Guid.NewGuid().ToString("N"), StoreLocation.CurrentUser))
     {
         Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly));
     }
 }
开发者ID:nadiatk,项目名称:corefx,代码行数:7,代码来源:X509StoreTests.cs

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

示例7: GetStoreCertificate

        /// <summary>
        /// Gets the store certificate matching the thumbprint. The algorithm looks in both the current user and local machine stores and returns the first occurrence. 
        /// </summary>
        /// <param name="thumbprint">The thumbprint.</param>
        /// <returns>Client certificate</returns>
        /// <exception cref="System.ArgumentException">A Certificate with Thumbprint '{0}' could not be located.</exception>
        private static X509Certificate2 GetStoreCertificate(string thumbprint)
        {
            var locations = new List<StoreLocation>
            {
                StoreLocation.CurrentUser,
                StoreLocation.LocalMachine
            };

            foreach(var location in locations)
            {
                var store = new X509Store("My", location);
                try
                {
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                    X509Certificate2Collection certificates = store.Certificates.Find(
                        X509FindType.FindByThumbprint,
                        thumbprint,
                        false);
                    if(certificates.Count == 1)
                    {
                        return certificates[0];
                    }
                }
                finally
                {
                    store.Close();
                }
            }

            throw new ArgumentException(string.Format(Resources.Errors.CertificateNotFound, thumbprint));
        }
开发者ID:afdabro,项目名称:HttpClientExtensions,代码行数:37,代码来源:CertificateHandler.cs

示例8: AddReadOnlyThrowsWhenCertificateExists

        public static void AddReadOnlyThrowsWhenCertificateExists()
        {
            using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2 toAdd = null;

                // Look through the certificates to find one with no private key to call add on.
                // (The private key restriction is so that in the event of an "accidental success"
                // that no potential permissions would be modified)
                foreach (X509Certificate2 cert in store.Certificates)
                {
                    if (!cert.HasPrivateKey)
                    {
                        toAdd = cert;
                        break;
                    }
                }

                if (toAdd != null)
                {
                    Assert.ThrowsAny<CryptographicException>(() => store.Add(toAdd));
                }
            }
        }
开发者ID:nadiatk,项目名称:corefx,代码行数:26,代码来源:X509StoreTests.cs

示例9: OpenMyStore

 public static void OpenMyStore()
 {
     using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
     {
         store.Open(OpenFlags.ReadOnly);
     }
 }
开发者ID:nadiatk,项目名称:corefx,代码行数:7,代码来源:X509StoreTests.cs

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

示例11: HttpClientExtensionsFixture

        public HttpClientExtensionsFixture()
        {
            var store = new X509Store(StoreName.TrustedPeople);

            store.Open(OpenFlags.ReadOnly);

            var certName = ConfigurationManager.AppSettings["AuthCertName"];

            this.certificate = store.Certificates.Cast<X509Certificate2>()
                .Single(c => c.Subject.Equals(certName));
        }
开发者ID:Georadix,项目名称:Georadix.NET,代码行数:11,代码来源:HttpClientExtensionsFixture.cs

示例12: RemoveCertificatesFromStore

	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() ; 
		}
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:12,代码来源:storebug.cs

示例13: ReadMyCertificates

        public static void ReadMyCertificates()
        {
            using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadOnly);
                int certCount = store.Certificates.Count;

                // This assert is just so certCount appears to be used, the test really
                // is that store.get_Certificates didn't throw.
                Assert.True(certCount >= 0);
            }
        }
开发者ID:nadiatk,项目名称:corefx,代码行数:12,代码来源:X509StoreTests.cs

示例14: GetEligibleClientCertificate

 public static X509Certificate2 GetEligibleClientCertificate()
 {
     // Get initial list of client certificates from the MY store.
     X509Certificate2Collection candidateCerts;
     using (var myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
     {
         myStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
         candidateCerts = myStore.Certificates;
     }
     
     return GetEligibleClientCertificate(candidateCerts);
 }
开发者ID:noahfalk,项目名称:corefx,代码行数:12,代码来源:WinHttpCertificateHelper.cs

示例15: GetCertificate

        private static X509Certificate2 GetCertificate(string thumbprint)
        {
            X509Store store = new X509Store("My", StoreLocation.LocalMachine);
            store.Open(OpenFlags.OpenExistingOnly);
            foreach (X509Certificate2 cert in store.Certificates)
            {
                if (cert.Thumbprint == thumbprint)
                    return cert;
            }

            return null;
        }
开发者ID:oanapl,项目名称:servicefabric-samples-1,代码行数:12,代码来源:ProxyHandler.cs


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