Open() public method

public Open ( OpenFlags flags ) : void
flags OpenFlags
return void
示例#1
0
        public static void RemoveCertificateFromLocalStoreByFriendlyName(string friendlyName, out bool removed)
        {
            removed = false;

            using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);

                // You could also use a more specific find type such as X509FindType.FindByThumbprint
                X509Certificate2Collection col =
                    store.Certificates;

                foreach (var cert in col)
                {
                    if (cert.FriendlyName == friendlyName)
                    {
                        store.Remove(cert);
                        TryRemovePrivateKey(cert);
                        removed = true;
                        break;
                    }
                }

                store.Close();
            }
        }
示例#2
0
        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);
        }
 private static X509Certificate GetServerCertificate()
 {
     X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
     store.Open(OpenFlags.ReadOnly);
     X509CertificateCollection cert = store.Certificates.Find(X509FindType.FindBySubjectName, "LocalHost", true);
     return cert[0];
 }
        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;
        }
        public static X509Certificate2 GetCertificate(string serialNumber)
        {
            List<string> list = new List<string>();
            X509Store storeCurUser = new X509Store(StoreLocation.CurrentUser);

            storeCurUser.Open(OpenFlags.ReadOnly);
            
            foreach (X509Certificate2 mCert in storeCurUser.Certificates)
            {
                if (mCert.SerialNumber.Contains(serialNumber))
                {
                    return mCert;
                }
            }

            X509Store storeMachine = new X509Store(StoreLocation.LocalMachine);

            storeMachine.Open(OpenFlags.ReadOnly);

            foreach (X509Certificate2 mCert in storeMachine.Certificates)
            {
                if (mCert.SerialNumber.Contains(serialNumber))
                {
                    return mCert;
                }
            }

            return null;
        }
示例#6
0
        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;
            }
        }
示例#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);
                }

                store.Close();

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

            throw new ArgumentException("No certificate can be found using the find value " + certFindValue);
        }
示例#8
0
        private static string GetEncryptionCertPrivateKey()
        {
            string privateKey = string.Empty;
            X509Store store = new X509Store("MY", StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

            X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
            X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, ConfigurationManager.AppSettings["EncryptionKeyCertThumbprint"], false);

            if (fcollection.Count != 1)
            {
                throw new InvalidOperationException("Could not find the cert or more than one certs found!");
            }

            foreach (X509Certificate2 x509 in fcollection)
            {
                try
                {
                    byte[] rawdata = x509.RawData;
                    privateKey = x509.PrivateKey.ToXmlString(false);
                    x509.Reset();
                }
                catch (CryptographicException)
                {
                    throw new InvalidOperationException("Information could not be retrieved out for this certificate.");
                }
            }
            store.Close();
            return privateKey;
        }
        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;
        }
        /// <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();
                }
            }
        }
示例#11
0
        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;
        }
        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");
        }
示例#13
0
        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;
        }
        public override BooleanReason Evaluate()
        {
            X509Store store = null;
            try
            {
                if (string.IsNullOrWhiteSpace(Thumbprint))
                    return new BooleanReason(false, "No thumbprint is specified");

                store = new X509Store(Store, Location);
                store.Open(OpenFlags.ReadOnly);

                foreach (var certificate in store.Certificates)
                {
                    if (string.IsNullOrWhiteSpace(certificate.Thumbprint))
                        continue;

                    if (certificate.Thumbprint.Equals(Thumbprint, StringComparison.InvariantCultureIgnoreCase))
                        return new BooleanReason(true, "Certificate matching thumbprint {0} found!");

                }

                return new BooleanReason(false, "No certificate matching thumbprint {0} found!");
            }
            catch (Exception e)
            {
                return new BooleanReason(false,
                                         "An issue occurred while attempting to locate certificate for thumbprint {0}: {1}",
                                         Thumbprint, e.Message);
            }
            finally
            {
                if (store !=null)
                    store.Close();
            }
        }
示例#15
0
 /// <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;
 }
示例#16
0
 /// <summary>
 /// Gets a X509 certificate from windows store. Asks the user for the correct certificate.
 /// </summary>
 /// <returns></returns>
 public static X509Certificate2 GetCertificate()
 {
     var st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
     st.Open(OpenFlags.ReadOnly);
     X509Certificate2 card = null;
     try
     {
         X509Certificate2Collection col = st.Certificates;
         X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificates",
                                          "Select one to sign",
                                          X509SelectionFlag.
                                          SingleSelection);
         if (sel.Count > 0)
         {
             X509Certificate2Enumerator en = sel.GetEnumerator();
             en.MoveNext();
             card = en.Current;
         }
     }
     finally
     {
         st.Close();
     }
     return card;
 }
示例#17
0
文件: TestHost.cs 项目: yxbdali/wcf
        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();
                }
            }
        }
 /// <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();
     }
 }
        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);
            }
        }
        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();
        }
        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;
        }
示例#22
0
        /// <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();
            }
        }
示例#23
0
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 LoadCertificate(EndpointConfiguration config, IWebHostEnvironment environment)
        {
            if (config.StoreName != null && config.StoreLocation != null)
            {
                using (var store = new System.Security.Cryptography.X509Certificates.X509Store(config.StoreName, Enum.Parse <StoreLocation>(config.StoreLocation)))
                {
                    store.Open(OpenFlags.ReadOnly);
                    var certificate = store.Certificates.Find(
                        X509FindType.FindBySubjectName,
                        config.Host,
                        validOnly: !environment.IsDevelopment());

                    if (certificate.Count == 0)
                    {
                        throw new InvalidOperationException($"Certificate not found for {config.Host}.");
                    }

                    return(certificate[0]);
                }
            }

            if (config.FilePath != null && config.Password != null)
            {
                return(new X509Certificate2(config.FilePath, config.Password));
            }

            throw new InvalidOperationException("No valid certificate configuration found for the current endpoint.");
        }
示例#24
0
        public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors.ToString() != "None")
            {
                MessageBox.Show("Please click yes on the next dialog box.\nThis will allow us to install the Net7 certificate.", "Certificate Install",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                try
                {
                    X509Store Certificate = new X509Store(StoreName.Root);

                    X509Certificate2 cert2 = new X509Certificate2(cert);

                    Certificate.Open(OpenFlags.ReadWrite);

                    // Add Certificate
                    Certificate.Add(cert2);
                    Certificate.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error installing certificate: " + e.ToString());
                }
            }
            else
            {
                MessageBox.Show("Certificate is installed!");
            }

            // Remove this message
            ServicePointManager.ServerCertificateValidationCallback = null;

            return true;
        }
        private void InstallWindows(MS509.X509Certificate2 cert)
        {
            var store = new MS509.X509Store(MS509.StoreName.My, MS509.StoreLocation.CurrentUser);

            store.Open(MS509.OpenFlags.ReadWrite);
            store.Add(cert);
        }
示例#26
0
        public static X509Certificate2 GetX509Certificate2(String thumbprint)
        {
            X509Certificate2 x509Certificate2 = null;

            X509Store store = new X509Store("My", StoreLocation.LocalMachine);

            try
            {
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection x509Certificate2Collection = store.Certificates.Find(X509FindType.FindByThumbprint,
                                                                                                thumbprint,
                                                                                                false);

                x509Certificate2 = x509Certificate2Collection[0];
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("Error in GetX509Certificate2(String thumbprint)  Error: {0}", ex.Message));

                x509Certificate2 = null;
            }
            finally
            {
                store.Close();
            }

            return x509Certificate2;
        }
        /// <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;
        }
        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();
            }
        }
示例#29
0
        /*
         * /// <summary>
         * /// Create a key pair
         * /// </summary>
         * /// <param name="pkSize">Key size</param>
         * /// <param name="pkAlgo">Key algorithm</param>
         * /// <param name="name">Key container name</param>
         * /// <returns></returns>
         * internal static CspParameters Create(int pkSize, string pkAlgo, string name)
         * {
         *  // Normalise the name
         *  string _name = name.Replace(' ', '_');
         *
         *  CspParameters cp = null;
         *  switch (pkAlgo)
         *  {
         *      case "RSA":
         *          cp = new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider");
         *          cp.KeyContainerName = _name;
         *          cp.Flags = CspProviderFlags.UseArchivableKey;
         *          using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(pkSize, cp))
         *          {
         *              rsa.PersistKeyInCsp = true;
         *              if (!rsa.CspKeyContainerInfo.Exportable)
         *                  throw new CryptoException("Key not exportable");
         *          }
         *          break;
         *      case "DSA":
         *          cp = new CspParameters(13, "Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider");
         *          cp.KeyContainerName = _name;
         *          cp.Flags = CspProviderFlags.UseArchivableKey;
         *          DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(pkSize, cp);
         *          dsa.PersistKeyInCsp = true;
         *          break;
         *      //case "ECDSA":
         *          //ECKeyPairGenerator ecGenerator = new ECKeyPairGenerator(pkAlgo);
         *          //ecGenerator.Init(genParam);
         *          //keyPair = ecGenerator.GenerateKeyPair();
         *          //break;
         *      default:
         *          throw new ArgumentException("Algorithm not supported", pkAlgo);
         *  }
         *  return cp;
         * }
         */
        #endregion


        //internal static X509Certificate storeKey(CspParameters cp, X509Certificate cert)
        internal static X509Certificate storeKey(X509Certificate cert)
        {
            //SysX509.X509KeyStorageFlags keyFlags = (SysX509.X509KeyStorageFlags.UserKeySet | SysX509.X509KeyStorageFlags.Exportable);
            //SysX509.X509KeyStorageFlags keyFlags = SysX509.X509KeyStorageFlags.Exportable;

            Sys.X509Certificate2 sCert = new Sys.X509Certificate2(cert.GetEncoded());

            Sys.X509Store store = new Sys.X509Store(Sys.StoreName.My,
                                                    Sys.StoreLocation.CurrentUser);
            store.Open(Sys.OpenFlags.MaxAllowed);
            store.Add(sCert);

            Sys.X509Certificate2Collection coll = store.Certificates.Find(Sys.X509FindType.FindBySerialNumber, sCert.SerialNumber, false);

            if (coll.Count > 1)
            {
                throw new CryptoException("Too many certs");
            }

            if (coll.Count < 1)
            {
                throw new CryptoException("Cert not found");
            }

            sCert = coll[0];
            if (!sCert.HasPrivateKey)
            {
                throw new CryptoException("No private key");
            }



            return(cert);
        }
示例#30
0
        private void Client()
        {

            SocketWatcher c_w = new SocketWatcher(20);
            c_w.Synchronous = true;

            // Note: must have a client cert in your IE cert store.
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            if (store.Certificates.Count > 0)
            {
                c_w.LocalCertificate = store.Certificates[0];
            }
            else
            {
                lock (done)
                {
                    errorMessage = "There were no certificates in the Windows Certificate Store.";
                    succeeded = false;
                    Monitor.Pulse(done);
                }

                return;
            }
            c_w.CreateConnectSocket(this, a, true, "localhost");
        }
示例#31
0
        /// <summary>
        /// Gets the physical certificates that match the input certificate from the Local Machine and Trusted People store.
        /// </summary>
        /// <param name="certificate"></param>
        /// <returns></returns>
        public static List<X509Certificate2> GetCertificates(Certificate certificate)
        {
            // If the certificate is null then we have none matching ?
            if (certificate == null)
                return null;

            X509Store x509Store;

            try
            {
                x509Store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
                x509Store.Open(OpenFlags.ReadOnly);
            }
            catch (Exception ex)
            {
                Logger.Error("Could not access certificate store.", ex);
                return null;
            }

            return x509Store.Certificates.Cast<X509Certificate2>().Where(c => (ContainsCondition(c.Issuer, certificate.Issuer)) &&
                                                                              (EqualCondition(c.GetPublicKeyString(), certificate.PublicKey)) &&
                                                                              (EqualCondition(c.GetSerialNumberString(), certificate.SerialNumber)) &&
                                                                              (ContainsCondition(c.Subject, certificate.Subject)) &&
                                                                              (EqualCondition(c.GetEffectiveDateString(), certificate.ValidFrom != DateTime.MinValue ? certificate.ValidFrom.ToString() : null)) &&
                                                                              (EqualCondition(c.GetExpirationDateString(), certificate.ValidTo != DateTime.MinValue ? certificate.ValidTo.ToString() : null))).ToList();
        }
示例#32
0
        //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);
        }
示例#33
0
        public async Task StartServerAsync()
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            //var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, "f864d23e92894c56df566b7ab7a9c6411d50d14d", false);
            var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, "3fd0b5f28dc32f5f0bb9f44cf1f6816846e44cbe", false);
            
            if (certificates.Count == 0)
            {
                throw new InvalidOperationException("Server certificate not found");
            }

            store.Close();
#if DEBUG
            ITraceWriter traceWriter = new DebugTraceWriter("Server"); 
#else
            ITraceWriter traceWriter = new FileTraceWriter("server.log"); 
#endif

            _listener = new TcpTransportListener(
                _listenerUri,
                certificates[0],
                new EnvelopeSerializer(),
                traceWriter
                );


            await _listener.StartAsync();
        }
 private static X509Certificate2 selectcert() //select cert from store & set selectedcert
 {
     try
     {
         if (File.Exists("c:\\hasher.cer"))
         {
             X509Certificate2 cert = new X509Certificate2("c:\\hasher.cer");
             appLog.WriteEntry("Selected Cert: " + cert.Subject, System.Diagnostics.EventLogEntryType.Information);
             return(cert);
         }
         else
         {
             System.Security.Cryptography.X509Certificates.X509Store mystore = new System.Security.Cryptography.X509Certificates.X509Store(StoreLocation.CurrentUser);
             mystore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
             X509Certificate2Collection certCollection     = (X509Certificate2Collection)mystore.Certificates;
             X509Certificate2Collection foundCollection    = (X509Certificate2Collection)certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
             X509Certificate2Collection selectedcollection = X509Certificate2UI.SelectFromCollection(foundCollection, "Select a Certificate.", "Select a Certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);
             if (selectedcollection.Count > 0)
             {
                 X509Certificate2 certz = selectedcollection[0];
                 appLog.WriteEntry("Selected Cert: " + certz.Subject, System.Diagnostics.EventLogEntryType.Information);
                 return(certz);
             }
             appLog.WriteEntry("No Cert Selected", System.Diagnostics.EventLogEntryType.Warning);
             return(null);
         }
     }
     catch (Exception e)
     {
         appLog.WriteEntry(e.Message + e.StackTrace, System.Diagnostics.EventLogEntryType.Warning);
         return(null);
     }
 }
示例#35
0
        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;
            }
        }
示例#36
0
        private void StoreCertificate(X509Name name, MSX509.X509Certificate2 certificate, MSX509.StoreName storeName)
        {
            MSX509.X509Store store = new MSX509.X509Store(storeName, store_);
            store.Open(MSX509.OpenFlags.ReadWrite);
            store.Add(certificate);
            store.Close();

            certificates_[name] = certificate;
        }
示例#37
0
        internal static void ImportFromP12(byte[] P12, string pkAlgo, string name, string Password)
        {
            Sys.X509Certificate2 certToImport = new Sys.X509Certificate2(P12, Password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);

            if (!certToImport.HasPrivateKey)
            {
                throw new ApplicationException("No private key in PKCS#12 file");
            }

            CspParameters cp = null;

            // Normalise the name
            string _name = name.Replace(' ', '_');

            switch (pkAlgo)
            {
            case "RSA":
                cp = new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider");
                cp.KeyContainerName = _name;
                cp.Flags            = CspProviderFlags.UseArchivableKey;
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    //certToImport.PrivateKey
                    //rsa.ImportParameters(certToImport.PrivateKey);
                    rsa.PersistKeyInCsp = true;
                    if (!rsa.CspKeyContainerInfo.Exportable)
                    {
                        throw new CryptoException("Key not exportable");
                    }
                }
                break;

            case "DSA":
                cp = new CspParameters(13, "Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider");
                cp.KeyContainerName = _name;
                cp.Flags            = CspProviderFlags.UseArchivableKey;
                break;

            default:
                throw new ArgumentException("Algorithm not supported", pkAlgo);
            }



            //certToImport.PrivateKey

            Sys.X509Store store = new Sys.X509Store(Sys.StoreName.My,
                                                    Sys.StoreLocation.CurrentUser);
            store.Open(Sys.OpenFlags.MaxAllowed);
            store.Add(certToImport);

            //certToImport.PrivateKey
            store.Close();
        }
        /// <summary>
        /// Loads the specified system keystore and puts
        /// the keys store in read-only mode
        /// </summary>
        /// <param name="storeName">one of the enum values </param>
        /// <param name="storelocation">one of the enum values</param>
        public void Load(SystemX509.StoreName storeName, SystemX509.StoreLocation storelocation)
        {
            ReadOnlyKeyStore = true;
            _listItems.Clear();
            var store = new SystemX509.X509Store(storeName, storelocation);

            store.Open(SystemX509.OpenFlags.ReadOnly);
            foreach (SystemX509.X509Certificate2 cert in store.Certificates)
            {
                AddEntry(cert.FriendlyName, DotNetUtilities.FromX509Certificate(cert), null);
            }
        }
示例#39
0
        private void StoreCertificate(string name, byte[] raw, RSA key, MSX509.StoreName storeName, MSX509.StoreLocation location)
        {
            PKCS12 p12 = BuildPkcs12(raw, key);

            MSX509.X509Certificate2 certificate = new MSX509.X509Certificate2(p12.GetBytes(), "advtools", MSX509.X509KeyStorageFlags.PersistKeySet | MSX509.X509KeyStorageFlags.MachineKeySet | MSX509.X509KeyStorageFlags.Exportable);

            MSX509.X509Store store = new MSX509.X509Store(storeName, location);
            store.Open(MSX509.OpenFlags.ReadWrite);
            store.Add(certificate);
            store.Close();

            certificates_[name] = certificate;
        }
示例#40
0
        internal static byte[] ExportToP12(CspParameters cspParam, X509Certificate cert, string password)
        {
            Sys.X509Certificate2 sysCert = new Sys.X509Certificate2(cert.GetEncoded());;

            Sys.X509Store store = new Sys.X509Store(Sys.StoreLocation.CurrentUser);
            store.Open(Sys.OpenFlags.ReadWrite);
            store.Add(sysCert);

            sysCert = store.Certificates[0];

            // Export the certificate including the private key.
            return(sysCert.Export(Sys.X509ContentType.Pkcs12, password));
        }
示例#41
0
 /*
  * installs certificate and key into windows registry
  */
 private static void InstallIntoRegistry(sys.X509Certificate2 windowsCertificate)
 {
     sys.X509Store store = new sys.X509Store();
     store.Open(sys.OpenFlags.ReadWrite);
     try
     {
         store.Add(windowsCertificate);
     }
     finally
     {
         store.Close();
     }
 }
        public static void SaveCertificateToWindowsStore(X509Certificates.X509Certificate2 cert)
        {
            var x509Store = new X509Certificates.X509Store(X509Certificates.StoreName.Root, X509Certificates.StoreLocation.CurrentUser);

            x509Store.Open(X509Certificates.OpenFlags.ReadWrite);

            try
            {
                x509Store.Add(cert);
            }
            finally
            {
                x509Store.Close();
            }
        }
示例#43
0
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 FindCert(string pkiinfo)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
            X509Certificate2Collection col = store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindBySerialNumber, pkiinfo, true);

            store.Close();
            if (col != null && col.Count > 0)
            {
                //if (col.Count > 1)

                return(col[0]);
            }
            throw new ConfigurationErrorsException("no certificates were found matching that serial number");
        }
示例#44
0
        /// <summary>
        /// Add a certificate to a store
        /// </summary>
        /// <param name="cert"></param>
        /// <param name="st"></param>
        /// <param name="sl"></param>
        /// <returns></returns>
        public static bool AddCertToStore(X509Certificate2 cert, StoreName st, StoreLocation sl)
        {
            try
            {
                X509Store store = new X509Store(st, sl);
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);
                store.Close();
            }
            catch
            {
                return(false);
            }

            return(true);
        }
示例#45
0
        public static bool SetupSsl(int port)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
            //Use the first cert to configure Ssl
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
            //Assumption is we have certs. If not then this call will fail :(
            try
            {
                bool found = false;
                foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 cert in store.Certificates)
                {
                    String certHash = cert.GetCertHashString();
                    //Only install certs issued for the machine and has the name as the machine name
                    if (cert.Subject.ToUpper().IndexOf(Environment.MachineName.ToUpper()) >= 0)
                    {
                        try
                        {
                            found = true;
                            //ExecuteNetsh(String.Format("set ssl -i 0.0.0.0:{1} -c \"MY\" -h {0}", certHash, port));
                            ExecuteNetsh(string.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}}", port, certHash, Guid.NewGuid().ToString()));
                        }
                        catch (Exception e)
                        {
                            return(false);
                        }
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                return(false);
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return(true);
        }
示例#46
0
        static public bool checkCertificateInstalled()
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByIssuerName, ConfirmedConstants.endPoint("www"), true);

            if (certs.Count > 0)
            {
                for (int i = 0; i < certs.Count; i++)
                {
                    if (certs[i].IssuerName.Name.ToString() == "CN=" + ConfirmedConstants.endPoint("www"))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
示例#47
0
        private static void SetSSLCer()
        {
            Fiddler.CertMaker.createRootCert();
            X509Certificate2 oRootCert = Fiddler.CertMaker.GetRootCertificate();//Returns the Root certificate that Fiddler uses to generate per-site certificates used for HTTPS interception.

            System.Security.Cryptography.X509Certificates.X509Store certStore = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.Root, StoreLocation.LocalMachine);
            certStore.Open(OpenFlags.ReadWrite);
            try
            {
                certStore.Add(oRootCert);
            }
            finally
            {
                certStore.Close();
            }
            Fiddler.FiddlerApplication.oDefaultClientCertificate = oRootCert;
            Fiddler.CONFIG.IgnoreServerCertErrors = true;
        }
示例#48
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);
        }
示例#49
0
        public bool AddCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
        {
            bool bRet = false;

            try
            {
                System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(st, sl);
                store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
                store.Add(cert);

                store.Close();
            }
            catch
            {
                throw;
            }

            return(bRet);
        }
示例#50
0
        public static void RemoveCertificateFromLocalStoreByThumbprint(string thumbPrint)
        {
            using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);

                // You could also use a more specific find type such as X509FindType.FindByThumbprint
                X509Certificate2Collection col =
                    store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);

                foreach (var cert in col)
                {
                    // Remove the certificate
                    store.Remove(cert);
                    TryRemovePrivateKey(cert);
                }

                store.Close();
            }
        }
示例#51
0
        public static X509Certificate2 FindCertificate(string certificateThumbprint)
        {
            X509Certificate2 foundCert = null;
            var store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);

            foreach (var cert in store.Certificates)
            {
                if (cert.Thumbprint.Equals(certificateThumbprint))
                {
                    foundCert = cert;
                    break;
                }
            }

            store.Close();

            return(foundCert);
        }
示例#52
0
        /// <summary>
        /// Find certificate in store
        /// </summary>
        /// <param name="thumbPrint"></param>
        /// <param name="storeName"></param>
        /// <param name="storeLocation"></param>
        /// <returns></returns>
        public static X509Certificate2 FindCertificate(string thumbPrint, StoreName storeName, StoreLocation storeLocation)
        {
            X509Certificate2 certificate = null;

            X509Store store = new X509Store(storeName, storeLocation);

            store.Open(OpenFlags.ReadOnly | OpenFlags.IncludeArchived);

            // You could also use a more specific find type such as X509FindType.FindByThumbprint
            X509Certificate2Collection col =
                store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);

            foreach (var cert in col)
            {
                certificate = cert;
            }

            store.Close();

            return(certificate);
        }
示例#53
0
        private static void SetWsusCertificate(IUpdateServer wServ)
        {
            //Self Signed Certifications creation by WSUS server is deprecated, need an workaround
            if (wServ.IsConnectionSecureForApiRemoting)
            {
                try
                {
                    String           secret = "Secure!";
                    X509Certificate2 cert   = CreateSelfSignedCertificate("Carteiro");
                    File.WriteAllBytes("C:\\carteiro.pfx", cert.Export(X509ContentType.Pfx, secret));
                    File.WriteAllBytes("C:\\carteiro.cer", cert.Export(X509ContentType.Cert));
                    SetWsusCertificate("C:\\carteiro.pfx", secret, wServ);

                    //Importing into other stores
                    System.Security.Cryptography.X509Certificates.X509Store authRootStore         = new System.Security.Cryptography.X509Certificates.X509Store("AuthRoot", System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
                    System.Security.Cryptography.X509Certificates.X509Store trustedPublisherStore = new System.Security.Cryptography.X509Certificates.X509Store("TrustedPublisher", System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);

                    authRootStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
                    trustedPublisherStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);

                    authRootStore.Add(cert);
                    trustedPublisherStore.Add(cert);

                    authRootStore.Close();
                    trustedPublisherStore.Close();

                    Console.WriteLine("INFO: certificates were succesfully imported into AuthRoot and Trusted Publisher stores");
                    Console.WriteLine("INFO: setting new WSUS Certificate finished!");
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("ERROR: " + e.Message);
                }
            }
            else
            {
                Console.Error.WriteLine("ERROR: this operation is not possible with an unsafe connection");
            }
        }
示例#54
0
 public bool CheckCertificate()
 {
     try
     {
         System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(StoreName.My, StoreLocation.LocalMachine);
         store.Open(OpenFlags.ReadOnly); // Dont forget. otherwise u will get an exception.
         X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "2020ImagingLtd", true);
         if (certs.Count > 0)
         {
             // Certificate is found.
             return(true);
         }
         else
         {
             return(false);
             // No Certificate found by that subject name.
         }
     }
     catch (Exception ex)
     { }
     return(false);
 }
 private static System.Security.Cryptography.X509Certificates.X509Certificate2 selectcert() //select cert from store & set selectedcert
 {
     try
     {
         System.Security.Cryptography.X509Certificates.X509Store mystore = new System.Security.Cryptography.X509Certificates.X509Store(StoreLocation.CurrentUser);
         mystore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
         X509Certificate2Collection certCollection     = (X509Certificate2Collection)mystore.Certificates;
         X509Certificate2Collection foundCollection    = (X509Certificate2Collection)certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
         X509Certificate2Collection selectedcollection = X509Certificate2UI.SelectFromCollection(foundCollection, "Select a Certificate.", "Select a Certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);
         if (selectedcollection.Count > 0)
         {
             X509Certificate2 certz = selectedcollection[0];
             return(certz);
         }
         return(null);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         return(null);
     }
 }
        public static X509Certificates.X509Certificate2 LoadCertificate(string hostname)
        {
            var x509Store = new X509Certificates.X509Store(X509Certificates.StoreName.Root, X509Certificates.StoreLocation.CurrentUser);

            x509Store.Open(X509Certificates.OpenFlags.ReadOnly);
            var inStr = $"CN={hostname}";

            try
            {
                foreach (var certificate in x509Store.Certificates)
                {
                    if (certificate.Subject.StartsWith(inStr))
                    {
                        return(certificate);
                    }
                }
            }
            finally
            {
                x509Store.Close();
            }
            return(null);
        }
示例#57
0
        /*private void WriteCertificate(string name, byte[] raw)
         * {
         *  using(FileStream stream = new FileStream(GetCertificateFilePath(name), FileMode.Create, FileAccess.Write))
         *      stream.Write(raw, 0, raw.Length);
         * }*/

        private MSX509.X509Certificate2 LoadCertificate(string name, MSX509.StoreName storeName, MSX509.StoreLocation location)
        {
            if (certificates_.ContainsKey(name))
            {
                return(certificates_[name]);
            }

            MSX509.X509Store store = new MSX509.X509Store(storeName, location);
            store.Open(MSX509.OpenFlags.ReadOnly);
            var certificates = store.Certificates.Find(MSX509.X509FindType.FindBySubjectName, name, true);

            store.Close();

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

            state_.Logger.Information("X509v3 '{0}' loaded from store", name);

            MSX509.X509Certificate2 certificate = certificates[0];
            certificates_[name] = certificate;
            return(certificate);
        }
        internal static void InstallCertificate(string certFile, System.Security.Cryptography.X509Certificates.StoreName store, string password)
        {
            Logger.EnteringMethod(store.ToString());
            try
            {
                System.Security.Cryptography.X509Certificates.X509Certificate2 certificate;
                if (!string.IsNullOrEmpty(password))
                {
                    certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certFile, password);
                }
                else
                {
                    certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certFile);
                }
                System.Security.Cryptography.X509Certificates.X509Store certStore = new System.Security.Cryptography.X509Certificates.X509Store(store, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);

                certStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
                certStore.Add(certificate);
                certStore.Close();
                Logger.Write("Successfuly imported in " + store.ToString());
            }
            catch (Exception ex)
            { Logger.Write("**** " + ex.Message); }
        }
示例#59
0
        private MSX509.X509Certificate2 LoadCertificate(X509Name name, MSX509.StoreName storeName, MSX509.StoreLocation location)
        {
            if (certificates_.ContainsKey(name))
            {
                return(certificates_[name]);
            }

            string dn = name.ToString();

            MSX509.X509Store store = new MSX509.X509Store(storeName, location);
            store.Open(MSX509.OpenFlags.ReadOnly);
            var certificates = store.Certificates.Find(MSX509.X509FindType.FindBySubjectDistinguishedName, dn, true);

            store.Close();

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

            MSX509.X509Certificate2 certificate = certificates[0];
            certificates_[name] = certificate;
            return(certificate);
        }
示例#60
0
        /// <summary>
        /// Establishes the SSL certificate we will use for communication with
        /// RPC clients and starts a seperate thread to listen for connections
        /// </summary>
        /// <param name="port">port to listen on</param>
        /// <param name="service">The KeePassRPCService the server should interact with.</param>
        public KeePassRPCServer(int port, KeePassRPCService service, KeePassRPCExt keePassRPCPlugin, bool useSSL)
        {
            _useSSL = useSSL;
            if (keePassRPCPlugin.logger != null)
            {
                keePassRPCPlugin.logger.WriteLine("Starting KPRPCServer");
            }
            Service          = service;
            KeePassRPCPlugin = keePassRPCPlugin;

            if (_useSSL)
            {
//                if (true)
                if (Type.GetType("Mono.Runtime") == null)
                {
                    _store = new System.Security.Cryptography.X509Certificates.X509Store();
                    _store.Open(OpenFlags.ReadWrite);

                    // Find any certificates in this user's certificate store and re-use
                    // them rather than suffer the overhead of creating an entirly new
                    // certificate. Our certificates are considered "invalid" by the
                    // store (probably becuase they are self-signed)
                    X509Certificate2Collection matchingCertificates = _store.Certificates
                                                                      .Find(X509FindType.FindBySubjectDistinguishedName,
                                                                            "CN=KeePassRPC certificate for " + Environment.MachineName, false);

                    //foreach (X509Certificate2 temp in matchingCertificates)
                    //    _store.Remove(temp);

                    //matchingCertificates = _store.Certificates
                    //    .Find(X509FindType.FindBySubjectDistinguishedName,
                    //        "CN=KeePassRPC TLS aaa for " + Environment.MachineName, false);

                    if (keePassRPCPlugin.logger != null)
                    {
                        keePassRPCPlugin.logger.WriteLine("Matching certificates from store: " + matchingCertificates.Count);
                    }
                    if (matchingCertificates.Count > 0)
                    {
                        _serverCertificate = matchingCertificates[0];
                    }
                    else
                    {
                        //_serverCertificate = (X509Certificate2)X509Certificate2.CreateFromCertFile(Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "KeePassRPC"), "cert.p12"));

                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Generating new certificate (MS).");
                        }
                        // We can use the MakeCert feature from Mono to generate a new
                        // certificate for use by this user on this machine. This means
                        // that every KeePassRPC user will establish TLS connections
                        // that are protected by a private key held on their own
                        // system, rather than a key that is disclosed in this open
                        // source code. NB: The local server is assumed to be secure!
                        PKCS12 p12  = MakeCertKPRPC.Generate("KeePassRPC certificate for " + Environment.MachineName, "KeePassRPC Automated Self-Signed Key Generator", keePassRPCPlugin);
                        byte[] cert = p12.GetBytes();
                        _serverCertificate = new X509Certificate2(cert, (string)null, X509KeyStorageFlags.PersistKeySet);
                        _store.Add(_serverCertificate);
                    }
                }
                else
                {
                    /*
                     * Problem 1:
                     *   For Linux/Mono, we cannot use the X509Store. It appears that only a .cer file is saved. That certificate does not include
                     *   the private key that we need for SSL. So we will need to save the key ourselves.
                     *
                     * Problem 2:
                     *   When using PKCS12 SaveToFile to save the key ourselves, it appears that it is not possible to save a private key that is not
                     *   password protected.
                     *
                     */
                    string certdir  = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "KeePassRPC");
                    string certfile = Path.Combine(certdir, "cert.p12");
                    _serverCertificate = null;

                    // Check if cert directory exists, if not, we need to create it
                    if (!System.IO.Directory.Exists(certdir))
                    {
                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Cert directory does not exist, creating " + certdir);
                        }

                        System.IO.Directory.CreateDirectory(certdir);

                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Cert directory created");
                        }
                    }
                    else
                    {
                        // Attempt to load cert
                        try {
                            if (keePassRPCPlugin.logger != null)
                            {
                                keePassRPCPlugin.logger.WriteLine("Looking for existing certificate (Mono)");
                            }
                            _serverCertificate = new X509Certificate2();
                            _serverCertificate.Import(certfile, pkcs12_password, X509KeyStorageFlags.PersistKeySet);
                            if (keePassRPCPlugin.logger != null)
                            {
                                keePassRPCPlugin.logger.WriteLine("Existing certificate loaded(Mono) : " + certfile);
                            }
                        }
                        catch (Exception ex) {
                            _serverCertificate = null;
                        }
                    }
                    // If we didn't load a cert, create one and save it
                    if (_serverCertificate == null)
                    {
                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Generating new certificate (Mono).");
                        }

                        PKCS12 p12 = MakeCertKPRPC.Generate("KeePassRPC certificate for " + Environment.MachineName, "KeePassRPC Automated Self-Signed Key Generator", pkcs12_password, keePassRPCPlugin);
                        p12.SaveToFile(certfile);
                        byte[] cert = p12.GetBytes();
                        _serverCertificate = new X509Certificate2(cert, pkcs12_password, X509KeyStorageFlags.PersistKeySet);
                        if (keePassRPCPlugin.logger != null)
                        {
                            keePassRPCPlugin.logger.WriteLine("Generated new certificate (Mono) : " + certfile);
                        }
                    }
                }
            }

            if (keePassRPCPlugin.logger != null)
            {
                keePassRPCPlugin.logger.WriteLine("Server certificate has private key? " + _serverCertificate.HasPrivateKey);
            }

            try
            {
                this._tcpListener  = new TcpListener(IPAddress.Loopback, port);
                this._listenThread = new Thread(new ThreadStart(ListenForClients));
                this._listenThread.Start();
                this._isListening = true; // just in case the main thread checks
                // for successful startup before the thread has got going.
            }
            catch (Exception e)
            {
                if (keePassRPCPlugin.logger != null)
                {
                    keePassRPCPlugin.logger.WriteLine("Failed to start TCP listener: " + e.ToString());
                }
            }
            if (keePassRPCPlugin.logger != null)
            {
                keePassRPCPlugin.logger.WriteLine("Started KPRPCServer");
            }
        }