Dispose() публичный Метод

public Dispose ( ) : void
Результат void
        public X509SecurityTokenProvider(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findValue)
        {
            if (findValue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue");
            }

            X509Store store = new X509Store(storeName, storeLocation);
            X509Certificate2Collection certificates = null;
            try
            {
                store.Open(OpenFlags.ReadOnly);
                certificates = store.Certificates.Find(findType, findValue, false);
                if (certificates.Count < 1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.CannotFindCert, storeName, storeLocation, findType, findValue)));
                }
                if (certificates.Count > 1)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.FoundMultipleCerts, storeName, storeLocation, findType, findValue)));
                }

                _certificate = new X509Certificate2(certificates[0].Handle);
            }
            finally
            {
                System.ServiceModel.Security.SecurityUtils.ResetAllCertificates(certificates);
                store.Dispose();
            }
        }
        /// <summary>
        /// Finds the cert having thumbprint supplied from store location supplied
        /// </summary>
        /// <param name="storeName"></param>
        /// <param name="storeLocation"></param>
        /// <param name="thumbprint"></param>
        /// <param name="validationRequired"></param>
        /// <returns>X509Certificate2</returns>
        public static X509Certificate2 FindCertificateByThumbprint(StoreName storeName, StoreLocation storeLocation, string thumbprint, bool validationRequired)
        {
            Guard.ArgumentNotNullOrWhiteSpace(thumbprint, nameof(thumbprint));

            var store = new X509Store(storeName, storeLocation);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validationRequired);
                if (col == null || col.Count == 0)
                {
                    throw new ArgumentException("certificate was not found in store");
                }

                return col[0];
            }
            finally
            {
#if NET451
                // IDisposable not implemented in NET451
                store.Close();
#else
                // Close is private in DNXCORE, but Dispose calls close internally
                store.Dispose();
#endif
            }
        }
Пример #3
0
        public static RsaCipher LoadFromX509Store(string friendlyName)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                foreach (var x509 in store.Certificates)
                {
                    var cn = x509.FriendlyName;
                    if (cn == friendlyName)
                    {
                        var key = new RsaCipherKey();
                        try
                        {
                            #if NETSTANDARD2_0
                            key.Public  = x509.GetRSAPublicKey();
                            key.Private = x509.GetRSAPrivateKey();
                            #endif

                            #if NETFX
                            key.Public  = (RSACryptoServiceProvider)x509.PublicKey.Key;
                            key.Private = (RSACryptoServiceProvider)x509.PrivateKey;
                            #endif
                        }
                        catch (Exception)
                        {
                            key.Dispose();
                            throw;
                        }

                        RsaCipher rsaCipher = new RsaCipher();
                        rsaCipher._key = key;
                        return(rsaCipher);
                    }
                }
            }
            finally
            {
                #if NETSTANDARD2_0
                store.Dispose();
                #endif
            }
            throw new InternalErrorException("Certificate not found: " + friendlyName);
        }
        internal static X509Certificate2 GetCertificate(StoreName name, StoreLocation location, string thumbprint) {
            var store = new X509Store(name, location);

            try {
                store.Open(OpenFlags.ReadOnly);

                var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);

                return certificates.OfType<X509Certificate2>().SingleOrDefault();
            }

            finally {
#if DNXCORE50
                store.Dispose();
#else
                store.Close();
#endif
            }
        }
        /// <summary>
        /// Searches the stores for certificate with subject name matching the host and path extracted from the applicationUri.
        /// </summary>
        /// <param name="description">The <see cref="ApplicationDescription"/>.</param>
        /// <param name="createIfNotFound">Creates a new self-signed certificate if one not found.</param>
        /// <returns>The certificate. </returns>
        public static X509Certificate2 GetCertificate(this ApplicationDescription description, bool createIfNotFound = true)
        {
            if (description == null)
            {
                throw new ArgumentNullException(nameof(description));
            }

            if (string.IsNullOrEmpty(description.ApplicationUri))
            {
                throw new ArgumentOutOfRangeException(nameof(description), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}'.");
            }

            string subjectName = null;

            UriBuilder appUri = new UriBuilder(description.ApplicationUri);
            if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host))
            {
                var path = appUri.Path.Trim('/');
                if (!string.IsNullOrEmpty(path))
                {
                    subjectName = $"CN={path}, DC={appUri.Host}";
                }
            }

            if (appUri.Scheme == "urn")
            {
                var parts = appUri.Path.Split(new[] { ':' }, 2);
                if (parts.Length == 2)
                {
                    subjectName = $"CN={parts[1]}, DC={parts[0]}";
                }
            }

            if (subjectName == null)
            {
                throw new ArgumentOutOfRangeException(nameof(description), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            X509Certificate2 clientCertificate = null;
            X509Store store = null;
            List<X509Certificate2> foundCerts = new List<X509Certificate2>();

            // First check the Local Machine store.
            store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            try
            {
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
                if (certs.Count > 0)
                {
                    foundCerts.AddRange(certs.OfType<X509Certificate2>());
                }
            }
            catch (Exception ex)
            {
                Log.Warn($"Error opening X509Store '{store}'. {ex.Message}");
            }
            finally
            {
                store.Dispose();
            }

            // Then check the Current User store.
            store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            try
            {
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, false);
                if (certs.Count > 0)
                {
                    foundCerts.AddRange(certs.OfType<X509Certificate2>());
                }
            }
            catch (Exception ex)
            {
                Log.Warn($"Error opening X509Store '{store}'. {ex.Message}");
            }
            finally
            {
                store.Dispose();
            }

            // Select the certificate that was created last.
            if (foundCerts.Count > 0)
            {
                clientCertificate = foundCerts.OrderBy(c => c.NotBefore).Last();
                Log.Info($"Found certificate '{subjectName}'.");
                return clientCertificate;
            }

            Log.Info($"Creating new certificate '{subjectName}'.");
            try
            {
                var pfx = CertificateGenerator.CreateSelfSignCertificatePfx(
                    subjectName,
                    DateTime.UtcNow,
                    DateTime.UtcNow.AddYears(25),
                    new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyCertSign, true),
                    new X509EnhancedKeyUsageExtension(new OidCollection { new Oid(EnhancedKeyUsageOids.ServerAuthentication), new Oid(EnhancedKeyUsageOids.ClientAuthentication) }, false),
                    new X509SubjectAlternateNameExtension(new[] { new X509AlternativeName { Type = X509AlternateNameType.Url, Value = description.ApplicationUri } }, true));

                clientCertificate = new X509Certificate2(pfx, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.DefaultKeySet);

                // add cert to Current User store.
                store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                try
                {
                    store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);
                    store.Add(clientCertificate);
                }
                catch (Exception ex)
                {
                    Log.Warn($"Error adding certificate to store '{store}'. {ex.Message}");
                }
                finally
                {
                    store.Dispose();
                }
            }
            catch (Exception ex)
            {
                Log.Warn($"Error creating certificate '{subjectName}'. {ex.Message}");
            }

            return clientCertificate;
        }
Пример #6
0
 static bool StoreContainsCertificate(StoreName storeName, X509Certificate2 certificate)
 {
     X509Store store = new X509Store(storeName, StoreLocation.CurrentUser);
     X509Certificate2Collection certificates = null;
     try
     {
         store.Open(OpenFlags.ReadOnly);
         certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false);
         return certificates.Count > 0;
     }
     finally
     {
         SecurityUtils.ResetAllCertificates(certificates);
         store.Dispose();
     }
 }
Пример #7
0
        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);
                }

#if DOTNET_CORE
                store.Dispose();
#else
                store.Close();
#endif
                if (collection.Count > 0)
                {
                    return collection[0];
                }
            }

            throw new ArgumentException("No certificate can be found using the find value.");            
        }
Пример #8
0
        static X509Certificate2 GetCertificate(StoreLocation storeLocation, StoreName storeName, string certFindValue)
        {
            X509Store store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection = store.Certificates.Find(
                X509FindType.FindBySubjectName,
                certFindValue,
                false);
            if (collection.Count == 0)
            {
                throw new ArgumentException("No certificate can be found using the find value " + certFindValue);
            }

#if DOTNET
            store.Dispose();
#else
            store.Close();
#endif
            return collection[0];
        }
Пример #9
0
        /// <summary>
        /// Get X509 certificate from the certificate store.
        /// </summary>
        /// <param name="certificateName">Certificate name.</param>
        /// <returns>Certificate with the specified name.</returns>
        private static X509Certificate GetX509Certificate(string certificateName)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            var certs = store.Certificates.Find(X509FindType.FindBySubjectName, certificateName, false);
#if NETSTANDARD
            store.Dispose();
#else
            store.Close();
#endif

            if (certs.Count == 0)
            {
                throw new DicomNetworkException("Unable to find certificate for " + certificateName);
            }

            return certs[0];
        }
Пример #10
0
        // 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;
            lock(s_certificateLock)
            {
                try
                {
                    store = new X509Store(storeName, storeLocation);
                    store.Open(OpenFlags.ReadWrite);
                    existingCert = CertificateFromThumbprint(store, certificate.Thumbprint);
                    if (existingCert == null)
                    {
                        store.Add(certificate);
                    }
                }
                finally
                {
                    if (store != null)
                    {
                        store.Dispose();
                    }
                }

                return existingCert == null;
            }
        }