Beispiel #1
0
        }     // End Sub UninstallCertificate

        /// <summary>
        ///     Make current machine trust the Root Certificate used by this proxy
        /// </summary>
        /// <param name="storeName"></param>
        /// <param name="storeLocation"></param>
        /// <param name="certificate"></param>
        public static void InstallCertificate(
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate
            , System.Security.Cryptography.X509Certificates.StoreName storeName
            , System.Security.Cryptography.X509Certificates.StoreLocation storeLocation

            )
        {
            if (certificate == null)
            {
                throw new System.Exception("Could not install certificate as it is null or empty.");
            }

            using (System.Security.Cryptography.X509Certificates.X509Store x509Store =
                       new System.Security.Cryptography.X509Certificates.X509Store(storeName, storeLocation))
            {
                // todo
                // also it should do not duplicate if certificate already exists
                try
                {
                    x509Store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
                    x509Store.Add(certificate);
                }
                catch (System.Exception e)
                {
                    throw new System.Exception("Failed to make system trust root certificate "
                                               + $" for {storeName}\\{storeLocation} store location. You may need admin rights.",
                                               e);
                }
                finally
                {
                    x509Store.Close();
                }
            } // End Using x509Store
        }     // End Sub InstallCertificate
Beispiel #2
0
        /// <summary>
        /// Attempts to install the given certificate in the host OS's trusted root store.
        /// </summary>
        /// <param name="certificate">
        /// The certificate to install.
        /// </param>
        /// <param name="overwrite">
        /// Whether or not to overwrite. If true, any and all certificates in the host OS store with
        /// a matching subject name will be deleted before the supplied certificate is installed.
        /// </param>
        public static void InstallCertificateInHostOsTrustStore(X509Certificate certificate, bool overwrite = false)
        {
            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Win32NT:
            {
                var store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.Root, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
                store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);

                if (overwrite)
                {
                    UninstallCertificateInHostOsTrustStore(certificate);
                }

                store.Add(new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded()));

                store.Close();
            }
            break;

            default:
            {
                throw new PlatformNotSupportedException("This operating system is currently unsupported.");
            }
            }
        }
Beispiel #3
0
 public static void EnumCertificates(
     string name
     , System.Security.Cryptography.X509Certificates.StoreLocation location)
 {
     using (System.Security.Cryptography.X509Certificates.X509Store store =
                new System.Security.Cryptography.X509Certificates.X509Store(name, location))
     {
         try
         {
             store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
             foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 certificate
                      in store.Certificates)
             {
                 PrintCertificateInfo(certificate);
             }
         }
         catch (System.Exception ex)
         {
             System.Console.WriteLine(ex.Message);
         }
         finally
         {
             store.Close();
         }
     }
 }
Beispiel #4
0
        } // End Function LoadRootCertificate

        /// <summary>
        ///     Remove the Root Certificate trust
        /// </summary>
        /// <param name="storeName"></param>
        /// <param name="storeLocation"></param>
        /// <param name="certificate"></param>
        public static void UninstallCertificate(
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate
            , System.Security.Cryptography.X509Certificates.StoreName storeName
            , System.Security.Cryptography.X509Certificates.StoreLocation storeLocation
            )
        {
            if (certificate == null)
            {
                throw new System.Exception("Could not remove certificate as it is null or empty.");
            }

            using (System.Security.Cryptography.X509Certificates.X509Store x509Store =
                       new System.Security.Cryptography.X509Certificates.X509Store(storeName, storeLocation))
            {
                try
                {
                    x509Store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
                    x509Store.Remove(certificate);
                }
                catch (System.Exception e)
                {
                    throw new System.Exception("Failed to remove root certificate trust "
                                               + $" for {storeLocation} store location. You may need admin rights.", e);
                }
                finally
                {
                    x509Store.Close();
                }
            } // End Using x509Store
        }     // End Sub UninstallCertificate
Beispiel #5
0
        FindCertificates(
            System.Security.Cryptography.X509Certificates.StoreName storeName
            , System.Security.Cryptography.X509Certificates.StoreLocation storeLocation
            , string findValue)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2Collection results = null;

            using (System.Security.Cryptography.X509Certificates.X509Store x509Store =
                       new System.Security.Cryptography.X509Certificates.X509Store(storeName, storeLocation))
            {
                try
                {
                    x509Store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.OpenExistingOnly);
                    results = x509Store.Certificates.Find(
                        System.Security.Cryptography.X509Certificates.X509FindType
                        .FindBySubjectDistinguishedName, findValue, false);
                }
                finally
                {
                    x509Store.Close();
                }
            } // End Using x509Store

            return(results);
        } // End Function FindCertificates
Beispiel #6
0
        protected static void AddCertToStore(X509Certificate2 cert, StoreName name, StoreLocation location)
        {
            X509Store store = new X509Store(name, location);

            store.Open(OpenFlags.ReadWrite);
            store.Add(cert);
            store.Close();
        }
        private static bool TryFindCertificatesInStore(string thumbprint,
                                                       System.Security.Cryptography.X509Certificates.StoreLocation location, out System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.My, location);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
            certificates = store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, thumbprint, false);
            store.Close();


            return(certificates.Count > 0);
        }
Beispiel #8
0
        /// <summary>
        /// Lädt ein Zertifikat in einen Zertifikatsspeicher
        /// </summary>
        /// <param name="certificate">Zertifikat</param>
        /// <param name="zertifikatziel">Bereich in dem Zertifikatsspeicher in dem das Zertifikat abgelegt werden soll</param>
        /// <param name="zertifikatspeicher">Zertifikatspeicher (Computerkonto, Benutzerkonto, Dienstkonto)</param>
        private static void LadeX509InZertifikatsspeicher(X509Certificate certificate,
                                                          string passwort,
                                                          System.Security.Cryptography.X509Certificates.StoreName zertifikatziel,
                                                          System.Security.Cryptography.X509Certificates.StoreLocation zertifikatspeicher)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2 tempCert =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded(),
                                                                                   passwort,
                                                                                   System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet);

            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(zertifikatziel, zertifikatspeicher);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
            store.Add(tempCert);
            store.Close();
        }
        public IEnumerable <System.Security.Cryptography.X509Certificates.X509Certificate2> Get(
            System.Security.Cryptography.X509Certificates.StoreName storeName
            , System.Security.Cryptography.X509Certificates.StoreLocation storeLocation)
        {
            List <System.Security.Cryptography.X509Certificates.X509Certificate2> certificates = null;

            System.Security.Cryptography.X509Certificates.X509Store x509Store = new System.Security.Cryptography.X509Certificates.X509Store(storeName, storeLocation);
            x509Store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);

            certificates = new List <System.Security.Cryptography.X509Certificates.X509Certificate2>(x509Store.Certificates.Count);
            for (int i = 0; i < x509Store.Certificates.Count - 1; i++)
            {
                certificates.Add(x509Store.Certificates[i]);
            }
            x509Store.Close();
            return(certificates);
        }
        public void writeCertificate(Org.BouncyCastle.X509.X509Certificate cert, long enrollmentID)
        {
            // converting from bouncycastle X509Certificate to  System.Security.Cryptography.X509Certificates.X509Certificate2
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2();
            certificate.Import(cert.GetEncoded());

            // Finding the corresponding privatekey from windows keystore using the container-name
            RSACryptoServiceProvider rsaPrivate = retrievePrivateKey(enrollmentID);

            // linking the retrieved private key to the certificate
            certificate.PrivateKey = rsaPrivate;

            // opening up the windows cert store because thats where I want to save it.
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.MaxAllowed);
            store.Add(certificate);
            store.Close();
        }
Beispiel #11
0
        //addCertToStore(MyRootCAcert, StoreName.Root, StoreLocation.LocalMachine);
        //addCertToStore(MyCert, StoreName.My, StoreLocation.LocalMachine);
        public static bool addCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
        {
            bool bRet = false;

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

                store.Close();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            return(bRet);
        }
Beispiel #12
0
        private void AddToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName storeName, string storeLocation)
        {
            System.Security.Cryptography.X509Certificates.StoreLocation location;

            if (storeLocation == "currentuser")
            {
                location = System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser;
            }
            else
            {
                location = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine;
            }

            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(storeName, location);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);
            store.Add(cert);
            store.Close();
        }
Beispiel #13
0
        public static bool ExportCertificate(
            string certificateName,
            string path,
            string storeName,
            System.Security.Cryptography.X509Certificates.StoreLocation location)
        {
            bool success = false;

            using (System.Security.Cryptography.X509Certificates.X509Store store =
                       new System.Security.Cryptography.X509Certificates.X509Store(storeName, location))
            {
                store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
                try
                {
                    System.Security.Cryptography.X509Certificates.X509Certificate2Collection certs
                        = store.Certificates.Find(
                              System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
                              certificateName, true
                              );

                    if (certs != null && certs.Count > 0)
                    {
                        byte[] data = certs[0].Export(
                            System.Security.Cryptography.X509Certificates.X509ContentType.Cert
                            );
                        success = WriteFile(data, path);
                    }
                }
                catch (System.Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                }
                finally
                {
                    store.Close();
                }
            }

            return(success);
        }
Beispiel #14
0
        public static void Test()
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            // System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls13;


            System.Security.Cryptography.X509Certificates.X509Store store =
                new System.Security.Cryptography.X509Certificates.X509Store(
                    System.Security.Cryptography.X509Certificates.StoreName.Root
                    );

            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadWrite);

            // Retrieve the certificate
            System.Security.Cryptography.X509Certificates.X509Certificate2Collection certs =
                store.Certificates.Find(
                    System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName
                    , "SSL-SERVER"
                    , false
                    ); // There is no result when vaildOnly = true.

            if (certs.Count == 0)
            {
                // return;

                // cert = new System.Security.Cryptography.X509Certificates.X509Certificate2();
                // foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 certificate in store.Certificates) { cert = certificate; break; }

                string[] altNames = SelfSignedCertificate.SelfSigned.GetAlternativeNames(new string[0]);
                byte[]   pfx      = SelfSignedCertificate.SelfSigned.CreateSelfSignedCertificate(altNames, "");

                cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(pfx, "",
                                                                                          System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
                                                                                          // | System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.EphemeralKeySet // Error !
                                                                                          );
            }
            else
            {
                cert = certs[0];
            }

            store.Close(); // Close the storage area.

            System.Net.Sockets.TcpListener server =
                new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 900);

            System.Threading.Thread thread_server = new System.Threading.Thread(
                new System.Threading.ParameterizedThreadStart(RunServer)
                );
            thread_server.Start(server);


            // client code
            using (System.Net.Sockets.TcpClient tc = new System.Net.Sockets.TcpClient())
            {
                string connectTo = "127.0.0.1";
                connectTo = "localhost";
                connectTo = "example.int";
                connectTo = System.Environment.MachineName;

                tc.Connect(connectTo, 900);

                System.Net.Security.SslStream stream = new System.Net.Security.SslStream(tc.GetStream(), false
                                                                                         , new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate)
                                                                                         )
                {
                    ReadTimeout  = IOTimeout,
                    WriteTimeout = IOTimeout
                };

                // stream.AuthenticateAsClient(connectTo, null, true);
                stream.AuthenticateAsClient(connectTo, certs, System.Security.Authentication.SslProtocols.Tls12, true);
                // stream.AuthenticateAsClient(connectTo, certs, System.Security.Authentication.SslProtocols.Tls13, true);


                // This is where you read and send data
                while (true)
                {
                    string echo = System.Console.ReadLine();
                    byte[] buff = System.Text.Encoding.UTF8.GetBytes(echo + "<EOF>");
                    stream.Write(buff, 0, buff.Length);
                    stream.Flush();
                    //tc.GetStream().Write(buff, 0, buff.Length);
                    //tc.GetStream().Flush();
                }

                // tc.Close();
            }
        }
        private static bool TryFindCertificatesInStore(string thumbprint,
                     System.Security.Cryptography.X509Certificates.StoreLocation location, out System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates)
        {
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.My, location);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
            certificates = store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, thumbprint, false);
            store.Close();


            return certificates.Count > 0;
        }