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


C# X509Store.Open方法代码示例

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


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

示例1: LookupCertificate

 /// <summary>
 /// Private Utility method to get a certificate from a given store
 /// </summary>
 /// <param name="storeName">Name of certificate store (e.g. My, TrustedPeople)</param>
 /// <param name="storeLocation">Location of certificate store (e.g. LocalMachine, CurrentUser)</param>
 /// <param name="subjectDistinguishedName">The Subject Distinguished Name of the certificate</param>
 /// <returns>The specified X509 certificate</returns>
 static X509Certificate2 LookupCertificate( StoreName storeName, StoreLocation storeLocation, string subjectDistinguishedName )
 {
     X509Store store = null;
     X509Certificate2Collection certs = null;
     X509Certificate2 certificate = null;
     try
     {
         store = new X509Store( storeName, storeLocation );
         store.Open( OpenFlags.ReadOnly );
         certs = store.Certificates.Find( X509FindType.FindBySubjectDistinguishedName,
                                                                    subjectDistinguishedName, false );
         if ( certs.Count != 1 )
         {
             throw new X509HelperException( String.Format( "FedUtil: Certificate {0} not found or more than one certificate found", subjectDistinguishedName ) );
         }
         certificate = new X509Certificate2( certs[0] );
         return certificate;
     }
     finally
     {
         if ( certs != null )
         {
             for ( int i = 0; i < certs.Count; ++i )
             {
                 certs[i].Reset();
             }
         }
         if ( store != null ) store.Close();
     }
 }
开发者ID:ramamurthyk,项目名称:CPrakash.Security.ActiveSTS,代码行数:37,代码来源:X509Helper.cs

示例2: GetACertificateWithPrivateKeyInStore

        private static X509Certificate2 GetACertificateWithPrivateKeyInStore(StoreName storeName, StoreLocation storeLocation)
        {
            Trace.WriteLine(string.Format("Looking for certificates in store : {0}, store location : {1}", storeName, storeLocation));

            var certificateStore = new X509Store(storeName, storeLocation);
            certificateStore.Open(OpenFlags.ReadOnly);
            foreach (var certificate in certificateStore.Certificates)
            {
                if (certificate.HasPrivateKey && certificate.PublicKey.Key.KeySize == 2048)
                {
                    try
                    {
                        var key = certificate.PrivateKey;
                        Trace.WriteLine("Found a suitable certificate with a private key");
                        Trace.WriteLine(string.Format("Certificate issuer : {0}, Subject Name : {1}", certificate.Issuer, certificate.Subject));
                        return certificate;
                    }
                    catch (Exception)
                    {
                        Trace.WriteLine("Ignoring a Cryptography Next generation (CNG) cert");
                    }
                }
            }

            return null;
        }
开发者ID:Xamarui,项目名称:Katana,代码行数:26,代码来源:X509CertificateTokenVerification.cs

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

示例4: LoadCertificateByThumbprint

        private bool LoadCertificateByThumbprint(string thumbprint)
        {
            thumbprint = thumbprint.Replace(" ", "").ToUpperInvariant();
            StoreName storeName = StoreName.My;
            StoreLocation storeLocation = StoreLocation.LocalMachine;
            X509Store store = new X509Store(storeName, storeLocation);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                foreach (var cert in store.Certificates)
                {
                    if (cert.HasPrivateKey == false)
                        continue;

                    if (String.Compare(cert.Thumbprint, thumbprint) == 0)
                    {
                        _certificate = cert;
                        break;
                    }
                }
            }
            finally
            {
                store.Close();
            }

            if (_certificate == null)
            {
                throw new InvalidOperationException("The certificate with the thumbprint " + thumbprint + " could not be found.");
            }

            return true;
        }
开发者ID:JulieGueho,项目名称:Encryption,代码行数:35,代码来源:EncryptionService.cs

示例5: Configuration

        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("Api", "{Controller}");
            config.EnableCors();

            var issuer = ConfigurationManager.AppSettings["Issuer"];
            var audience = ConfigurationManager.AppSettings["Audience"];
            var signingCertificateSubjectDistinguishedName = ConfigurationManager.AppSettings["SigningCertificateSubjectDistinguishedName"];

            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);
            var certificate = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, signingCertificateSubjectDistinguishedName, true)[0];

            // JSON should serialize to camelCase, not PascalCase (the default)
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] {audience},
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new X509CertificateSecurityTokenProvider(issuer, certificate),
                        //new X509CertificateSecurityTokenProvider(issuer, new X509Certificate2("PATH_TO_YOUR_PUBLIC_CERTIFICATE.cer")),
                    },
                });

            app.UseWebApi(config);
        }
开发者ID:altenstedt,项目名称:OpKoKo.15.2.WebApi,代码行数:34,代码来源:Startup.cs

示例6: CreateCredentialAsync

        /// <summary>
        /// Handle challenges for a secured resource by prompting for a client certificate
        /// </summary>
        public async Task<Credential> CreateCredentialAsync(CredentialRequestInfo info)
        {
            Credential credential = null;

            try
            {
                // Use the X509Store to get available certificates
                var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);
                var certificates = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);

                // Ask the user to select a certificate to use
                certificates = X509Certificate2UI.SelectFromCollection(certificates, "Select Certificate",
                    "Select the certificate to use for authentication.", X509SelectionFlag.SingleSelection);

                // Create a new CertificateCredential using the chosen certificate
                credential = new CertificateCredential(certificates[0])
                {
                    ServiceUri = SecuredPortalUrl
                };

            }
            catch (Exception ex)
            { 
                Debug.WriteLine("Exception: " + ex.Message); 
            }

            // Return the CertificateCredential for the secured portal
            return credential;
        }
开发者ID:MagicWang,项目名称:arcgis-runtime-samples-dotnet,代码行数:33,代码来源:MainWindow.xaml.cs

示例7: GetAppleServerCert

        private static X509Certificate GetAppleServerCert(string thumbprint)
        {
            X509Store store;
            store = new X509Store(StoreLocation.CurrentUser);

            if (store != null)
            {
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection certs = store.Certificates;

                if (certs.Count > 0)
                {
                    for (int i = 0; i < certs.Count; i++)
                    {
                        X509Certificate2 cert = certs[i];

                        if (cert.Thumbprint.Equals(thumbprint, StringComparison.InvariantCultureIgnoreCase))
                        {
                            return certs[i];
                        }
                    }
                }
            }

            Trace.TraceError("Could not find the certification containing: {0} ", "R5QS56362W:R5QS56362W");

            throw new InvalidDataException("Could not find the Apple Push Notification certificate");
        }
开发者ID:joe-keane,项目名称:dotnet-passbook,代码行数:29,代码来源:SendEmptyPushNotification.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);
                foreach (var cert in Certificates)
                {
                    if (store.Certificates.Contains(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:nism,项目名称:LoLNotes,代码行数:26,代码来源:CertificateInstaller.cs

示例10: SignN3Gost

        //INFO: метод для тестирования
        public string SignN3Gost(string data)
        {
            var storeCurrentUser = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            storeCurrentUser.Open(OpenFlags.ReadOnly);

            var coll = storeCurrentUser.Certificates
                                       .Find(X509FindType.FindByThumbprint, "4d 19 79 84 52 9a 80 4a c4 86 3a 82 6a 8d ab 85 3f 95 e5 01", false)[0];
            //b8 be f8 22 e8 63 2a 74 d4 2e 58 df 91 9c 2f e3 75 ea e1 e4 просрочен
            //4d 19 79 84 52 9a 80 4a c4 86 3a 82 6a 8d ab 85 3f 95 e5 01
            var gost = (Gost3410CryptoServiceProvider) coll.PrivateKey;

            var base64Blob = Convert.ToBase64String(coll.Export(X509ContentType.Cert));

            var gostSignatureFormatter = new GostSignatureFormatter(gost);
            gostSignatureFormatter.SetHashAlgorithm("Gost3411");

            var hash = Md5Helper.GetGost3411Hash(data);
            var base64Hash = Convert.ToBase64String(hash);
            var sign = gostSignatureFormatter.CreateSignature(hash);
            var base64Sign = Convert.ToBase64String(sign);

            var signData = new SignData
                           {
                               data = data,
                               public_key = base64Blob,
                               hash = base64Hash,
                               sign = base64Sign
                           };

            return JsonConvert.SerializeObject(signData);
        }
开发者ID:nbIxMaN,项目名称:RestTest,代码行数:32,代码来源:SignatureHelper.cs

示例11: InstallCertificate

        private static void InstallCertificate(StringDictionary parametrs)
        {
            try
            {
                string[] param = parametrs["assemblypath"].Split('\\');
                string certPath = String.Empty;

                for (int i = 0; i < param.Length - 1; i++)
                {
                    certPath += param[i] + '\\';
                }
                certPath += "certificate.pfx";

                var cert = new X509Certificate2(certPath, "",
                  X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

                var store = new X509Store(StoreName.AuthRoot, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);
                store.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Certificate appeared to load successfully but also seems to be null.", ex);
            }
        }
开发者ID:kapryeong,项目名称:HTTP-SPEED-PLUS-MOBILITY,代码行数:26,代码来源:InstallerCertificate.cs

示例12: GetCertificate

        /// <summary>
        /// Opens the certificate from its store.
        /// </summary>
        /// <returns>The <see cref="X509Certificate2"/>.</returns>
        public X509Certificate2 GetCertificate()
        {
            if (Certificate != null) return Certificate;
            var store = new X509Store(StoreName, StoreLocation);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                var found = store.Certificates.Find(X509FindType, FindValue, ValidOnly);
                if (found.Count == 0)
                {
                    throw new ConfigurationErrorsException(string.Format(ErrorMessages.CertificateNotFound, FindValue));
                }

                if (found.Count > 1)
                {
                    throw new ConfigurationErrorsException(string.Format(ErrorMessages.CertificateNotUnique, FindValue));
                }
                Certificate = found[0];
                return found[0];
            }
            finally
            {
                store.Close();
            }
        }
开发者ID:jbparker,项目名称:SAML2,代码行数:29,代码来源:CertificateElement.cs

示例13: TryResolveCertificate

        internal static bool TryResolveCertificate(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, out X509Certificate2 certificate)
        {
            X509Store store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadOnly);

            certificate = null;
            X509Certificate2Collection certs = null;
            X509Certificate2Collection matches = null;
            try
            {
                certs = store.Certificates;
                matches = certs.Find(findType, findValue, false);

                // Throwing InvalidOperationException here, following WCF precedent. 
                // Might be worth introducing a more specific exception here.
                if (matches.Count == 1)
                {
                    certificate = new X509Certificate2(matches[0]);
                    return true;
                }
            }
            finally
            {
                CryptoHelper.ResetAllCertificates(matches);
                CryptoHelper.ResetAllCertificates(certs);
                store.Close();
            }

            return false;
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:30,代码来源:X509Util.cs

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

示例15: GetCertificate

        public X509Certificate2 GetCertificate(string thumbprint, StoreLocation storeLocation)
        {
            X509Store certStore = new X509Store(StoreName.My, storeLocation);
            X509Certificate2 certToUse = null;
            try
            {
                try
                {
                    certStore.Open(OpenFlags.ReadOnly);
                }
                catch (Exception ex)
                {
                    var outerEx = new Exception("Failed to open X509Store My on CurrentUser.", ex);
                    throw outerEx;
                }
                var primaryCertificateThumbprint = thumbprint.ToLower();

                var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, primaryCertificateThumbprint, false);
                if (certCollection == null || certCollection.Count == 0)
                {
                    return null;
                }
                certToUse = certCollection[0];
                if (certToUse.Thumbprint.ToLower() != primaryCertificateThumbprint.ToLower())
                {
                    return null;
                }
            }
            finally
            {
                certStore.Close();
            }
            return certToUse;
        }
开发者ID:compliashield,项目名称:certificate-issuer,代码行数:34,代码来源:CetificateStore.cs


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