Пример #1
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.");
            }
            }
        }
Пример #2
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
        public bool DoesExist()
        {
            bool FoundCertificate = false;

            foreach (var storeValue in Enum.GetValues(typeof(System.Security.Cryptography.X509Certificates.StoreName)))
            {
                // Superfish should be in "Root" or "AuthRoot", but check ALL to be safe
                System.Security.Cryptography.X509Certificates.X509Store store =
                    new System.Security.Cryptography.X509Certificates.X509Store((System.Security.Cryptography.X509Certificates.StoreName)storeValue);

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

                foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 mCert in store.Certificates)
                {
                    if (IsSuperfishCert(mCert))
                    {
                        Logging.Logger.Log(Logging.LogSeverity.Information, "Found Superfish certificate - Store: " + storeValue.ToString());
                        Logging.Logger.Log(Logging.LogSeverity.Information, "  Certificate: " + mCert.Issuer);
                        FoundCertificate = true;
                        break;
                    }
                }
            }

            return(FoundCertificate);
        }
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 GetCertificate()
        {
            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.ReadOnly | System.Security.Cryptography.X509Certificates.OpenFlags.OpenExistingOnly);

            System.Security.Cryptography.X509Certificates.X509Certificate2Collection collection = store.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByTimeValid, DateTime.Now, false);
            collection = collection.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByIssuerName, "skbkontur.ru", false);
            System.Security.Cryptography.X509Certificates.X509Certificate2Collection scollection = null;

            while (true)
            {
                scollection = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(collection, "Установленные на ПК сертификаты ЗАО ПФ СКБ Контур", "Сделайте выбор сертификата для подписания документов в системе диадок", System.Security.Cryptography.X509Certificates.X509SelectionFlag.MultiSelection);
                if (scollection.Count == 0)
                {
                    throw new Exception("Внимание!!!: Сертификат не выбран!");
                }
                if (scollection.Count == 1)
                {
                    Console.WriteLine("Выбран сертификат: {0}", scollection[0].FriendlyName);
                    break;
                }
                if (scollection.Count > 1)
                {
                    Console.WriteLine("Внимание!!!: Выбрано более одного сертификата!\nСделайте уникальный выбор из доступных сертификатов для аутентификации в системе диадок.");
                    continue;
                }
                break;
            }
            return(scollection[0]);
        }
Пример #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
Пример #6
0
        // CurrentUser.My:/root/.dotnet/corefx/cryptography/x509stores/my
        // CurrentUser.Root:/root/.dotnet/corefx/cryptography/x509stores/root
        public static void ListCertificates()
        {
            System.Console.WriteLine("\r\nExists Certs Name and Location");
            System.Console.WriteLine("------ ----- -------------------------");

            foreach (System.Security.Cryptography.X509Certificates.StoreLocation storeLocation in (System.Security.Cryptography.X509Certificates.StoreLocation[])
                     System.Enum.GetValues(typeof(System.Security.Cryptography.X509Certificates.StoreLocation)))
            {
                foreach (System.Security.Cryptography.X509Certificates.StoreName storeName in (System.Security.Cryptography.X509Certificates.StoreName[])
                         System.Enum.GetValues(typeof(System.Security.Cryptography.X509Certificates.StoreName)))
                {
                    using (System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(storeName, storeLocation))
                    {
                        try
                        {
                            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.OpenExistingOnly);
                            string path = GetPath(store);
                            System.Console.WriteLine("{0}.{1}:{2}", storeLocation, storeName, path);
                            // Console.WriteLine("Yes {0,4}  {1}, {2}", store.Certificates.Count, store.Name, store.Location);
                        }
                        catch (System.Security.Cryptography.CryptographicException)
                        {
                            // Console.WriteLine("No {0}, {1}", store.Name, store.Location);
                        }
                    } // End Using store
                }     // Next storeName

                System.Console.WriteLine();
            } // Next storeLocation
        }     // End Sub ListCertificates
Пример #7
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
Пример #8
0
        public static bool certExists()
        {
            // TODO:
            // StoreLocation.CurrentUser)

            using (System.Security.Cryptography.X509Certificates.X509Store 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.ReadOnly);

                System.Security.Cryptography.X509Certificates.X509Certificate2Collection certificates =
                    store.Certificates.Find(
                        System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
                        "subjectName",
                        false
                        );

                if (certificates != null && certificates.Count > 0)
                {
                    System.Console.WriteLine("Certificate already exists");
                    return(true);
                }
            }

            return(false);
        }
        public bool DoesExist()
        {
            bool FoundCertificate = false;

            foreach (var storeValue in Enum.GetValues(typeof(System.Security.Cryptography.X509Certificates.StoreName)))
            {
                // Superfish should be in "Root" or "AuthRoot", but check ALL to be safe
                System.Security.Cryptography.X509Certificates.X509Store store =
                    new System.Security.Cryptography.X509Certificates.X509Store((System.Security.Cryptography.X509Certificates.StoreName) storeValue);

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

                foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 mCert in store.Certificates)
                {
                    if (IsSuperfishCert(mCert))
                    {
                        Logging.Logger.Log(Logging.LogSeverity.Information, "Found Superfish certificate - Store: " + storeValue.ToString());
                        Logging.Logger.Log(Logging.LogSeverity.Information, "  Certificate: " + mCert.Issuer);
                        FoundCertificate = true;
                        break;
                    }
                }
            }

            return FoundCertificate;
        }
Пример #10
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();
         }
     }
 }
Пример #11
0
        public static string GetPath(System.Security.Cryptography.X509Certificates.X509Store store)
        {
            System.Type t = typeof(System.Security.Cryptography.X509Certificates.X509Store);
            System.Reflection.FieldInfo fi = t.GetField("_storePal"
                                                        , System.Reflection.BindingFlags.Instance
                                                        | System.Reflection.BindingFlags.NonPublic
                                                        );

            object obj = fi.GetValue(store);

            // System.Console.WriteLine(obj);

            // System.Type tt = System.Type.GetType("Internal.Cryptography.Pal.DirectoryBasedStoreProvider, System.Security.Cryptography.X509Certificates");
            System.Type tt = obj.GetType();
            // System.Console.WriteLine(obj);

            // private readonly string _storePath;
            System.Reflection.FieldInfo fi2 = tt.GetField("_storePath"
                                                          , System.Reflection.BindingFlags.Instance
                                                          | System.Reflection.BindingFlags.NonPublic
                                                          | System.Reflection.BindingFlags.FlattenHierarchy);


            if (fi2 != null)
            {
                // object obj2 = fi2.GetValue(System.Convert.ChangeType(obj, tt));
                object obj2 = fi2.GetValue(obj);
                string path = System.Convert.ToString(obj2);
                return(path);
            }

            return(null);
        }
        /// <summary>
        /// Find a certificate in the Personal area of the cert store, by thumbprint
        /// </summary>
        /// <param name="theThumbprint"></param>
        /// <param name="theCertStoreName"</param>
        /// <returns></returns>
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 FindCertByThumbprint(string theThumbprint,
                                                                                                           System.Security.Cryptography.X509Certificates.StoreName theCertStoreName,
                                                                                                           System.Security.Cryptography.X509Certificates.StoreLocation theCertLocation,
                                                                                                           bool SearchOnlyValidCerts)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2           theCert = null;
            System.Security.Cryptography.X509Certificates.X509Certificate2Collection allCerts;
            System.Security.Cryptography.X509Certificates.X509Store theStore = new System.Security.Cryptography.X509Certificates.X509Store(theCertStoreName, theCertLocation);
            theStore.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);

            allCerts = theStore.Certificates.Find(System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, theThumbprint, SearchOnlyValidCerts);
            foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 someCert in allCerts)
            {
                // take the first one found, it should be the only one matching the thumbprint anyway
                theCert = someCert;
                break;
            }

            if (null == theCert)
            {
                throw new System.Security.Cryptography.CryptographicException("Requested X509 certificate not found in requested store.");
            }

            return(theCert);
        }
Пример #13
0
        private byte[] GetCACertsFromStore()
        {
            // get list of known CAs as Issuer certs from cert store
            // derived from PR idea by @pkiguy https://github.com/webprofusion/certify/pull/340

            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.ReadOnly);
            var allCACerts = store.Certificates;

            using (var writer = new StringWriter())
            {
                var pemWriter  = new PemWriter(writer);
                var certParser = new X509CertificateParser();

                foreach (var c in allCACerts)
                {
                    Org.BouncyCastle.X509.X509Certificate parsedCert = certParser.ReadCertificate(c.GetRawCertData());
                    pemWriter.WriteObject(parsedCert);
                }

                writer.Flush();
                return(System.Text.ASCIIEncoding.ASCII.GetBytes(writer.ToString()));
            }
        }
Пример #14
0
        /// <summary>
        /// Attempts to remove any and all certificates in the host OS's trusted root cert store that
        /// has the same subject name as the given certificate.
        /// </summary>
        /// <param name="certificate">
        /// The certificate who's subject name to use for matching certificates that need to be removed.
        /// </param>
        public static void UninstallCertificateInHostOsTrustStore(X509Certificate certificate)
        {
            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);

                foreach (var storeCert in store.Certificates)
                {
                    if (storeCert.SubjectName.Format(false) == certificate.SubjectDN.ToString())
                    {
                        // Cert with same subject exists. Remove.
                        store.Remove(storeCert);
                    }
                }
            }
            break;

            default:
            {
                throw new PlatformNotSupportedException("This operating system is currently unsupported.");
            }
            }
        }
Пример #15
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);
        }
Пример #17
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 static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

            File.Copy(dataDir + "blank.pdf", dataDir + "externalSignature1.pdf", true);
            using (FileStream fs = new FileStream(dataDir + "externalSignature1.pdf", FileMode.Open, FileAccess.ReadWrite))
            {
                using (Document doc = new Document(fs))
                {
                    SignatureField field1 = new SignatureField(doc.Pages[1], new Rectangle(100, 400, 10, 10));

                    // Sign with certificate selection in the windows certificate store
                    System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
                    store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
                    // Manually chose the certificate in the store
                    System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);

                    Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0])
                    {
                        Authority   = "Me",
                        Reason      = "Reason",
                        ContactInfo = "Contact"
                    };

                    field1.PartialName = "sig1";
                    doc.Form.Add(field1, 1);
                    field1.Sign(externalSignature);
                    doc.Save();
                }
            }

            using (PdfFileSignature pdfSign = new PdfFileSignature(new Document(dataDir + "externalSignature1.pdf")))
            {
                IList <string> sigNames = pdfSign.GetSignNames();
                for (int index = 0; index <= sigNames.Count - 1; index++)
                {
                    if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
                    {
                        throw new ApplicationException("Not verified");
                    }
                }
            }
            // ExEnd:1
        }
        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);
        }
Пример #20
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();
        }
Пример #21
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);
        }
        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();
        }
Пример #23
0
        /// <summary>
        /// Lädt ein Zertifikat aus dem lokalen Zertifikatsspeicher des Computerkontos. Gesucht wird in em Bereich eigene Zertifikate
        /// </summary>
        /// <param name="anzeigenname"></param>
        /// <returns></returns>
        public static X509Certificate LadeX509AusMaschinenStore(string antragsteller)
        {
            X509Certificate certificate = null;

            System.Security.Cryptography.X509Certificates.X509Store store =
                new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.TrustedPeople,
                                                                            System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);

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

            foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 cert in store.Certificates)
            {
                if (cert.Subject.Contains(antragsteller))
                {
                    return(DotNetUtilities.FromX509Certificate(cert));
                }
            }

            return(certificate);
        }
        public bool Remove()
        {
            bool FoundSuperfishCert         = false;
            bool ProblemDeletingCertificate = false;

            foreach (var storeValue in Enum.GetValues(typeof(System.Security.Cryptography.X509Certificates.StoreName)))
            {
                // Superfish should be in "Root" or "AuthRoot", but check ALL to be safe
                System.Security.Cryptography.X509Certificates.X509Store store =
                    new System.Security.Cryptography.X509Certificates.X509Store((System.Security.Cryptography.X509Certificates.StoreName)storeValue);

                //StorePermission sp = new StorePermission(PermissionState.Unrestricted);
                //sp.Flags = StorePermissionFlags.OpenStore;

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

                foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 mCert in store.Certificates)
                {
                    if (IsSuperfishCert(mCert))
                    {
                        FoundSuperfishCert = true;

                        Logging.Logger.Log(Logging.LogSeverity.Information, "Found Superfish certificate - Store: " + storeValue.ToString());
                        try
                        {
                            Logging.Logger.Log(Logging.LogSeverity.Information, "  DELETING Certificate: " + mCert.Issuer);
                            store.Remove(mCert);
                        }
                        catch (Exception ex)
                        {
                            ProblemDeletingCertificate = true;

                            Logging.Logger.Log(ex, "  Exception deleting certificate: " + ex.ToString());
                            //throw;
                        }
                    }
                }
            }

            return(FoundSuperfishCert && (!ProblemDeletingCertificate));
        }
Пример #25
0
        public bool Remove()
        {
            bool FoundSuperfishCert = false;
            bool ProblemDeletingCertificate = false;

            foreach (var storeValue in Enum.GetValues(typeof(System.Security.Cryptography.X509Certificates.StoreName)))
            {
                // Superfish should be in "Root" or "AuthRoot", but check ALL to be safe
                System.Security.Cryptography.X509Certificates.X509Store store =
                    new System.Security.Cryptography.X509Certificates.X509Store((System.Security.Cryptography.X509Certificates.StoreName)storeValue);

                //StorePermission sp = new StorePermission(PermissionState.Unrestricted);
                //sp.Flags = StorePermissionFlags.OpenStore;

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

                foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 mCert in store.Certificates)
                {
                    if (IsSuperfishCert(mCert))
                    {
                        FoundSuperfishCert = true;

                        Logging.Logger.Log(Logging.LogSeverity.Information, "Found Superfish certificate - Store: " + storeValue.ToString());
                        try
                        {
                            Logging.Logger.Log(Logging.LogSeverity.Information, "  DELETING Certificate: " + mCert.Issuer);
                            store.Remove(mCert);
                        }
                            catch (Exception ex)
                        {
                            ProblemDeletingCertificate = true;

                            Logging.Logger.Log(ex, "  Exception deleting certificate: " + ex.ToString());
                            //throw;
                        }
                    }
                }
            }

            return (FoundSuperfishCert && (!ProblemDeletingCertificate));
        }
Пример #26
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);
        }
Пример #27
0
        } // End Sub TrustRootCertificate

        private static System.Security.Cryptography.X509Certificates.X509Certificate Find(
            string serialNumber, System.Security.Cryptography.X509Certificates.StoreLocation location)
        {
            using (System.Security.Cryptography.X509Certificates.X509Store store =
                       new System.Security.Cryptography.X509Certificates.X509Store(location))
            {
                store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.OpenExistingOnly);
                System.Security.Cryptography.X509Certificates.X509Certificate2Collection certs =
                    store.Certificates.Find(
                        System.Security.Cryptography.X509Certificates.X509FindType
                        .FindBySerialNumber, serialNumber, true);

                //return certs.OfType<X509Certificate>().FirstOrDefault();

                foreach (System.Security.Cryptography.X509Certificates.X509Certificate2 thisCertificate
                         in certs)
                {
                    return(thisCertificate);
                }
            }

            return(null);
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();

            Document doc = new Document(dataDir + "blank.pdf");

            using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature())
            {
                pdfSign.BindPdf(doc);

                // Sign with certificate selection in the windows certificate store
                System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
                store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
                // Manually chose the certificate in the store
                System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);

                Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0]);
                pdfSign.SignatureAppearance = dataDir + "demo.png";
                pdfSign.Sign(1, "Reason", "Contact", "Location", true, new System.Drawing.Rectangle(100, 100, 200, 200), externalSignature);
                pdfSign.Save(dataDir + "externalSignature2.pdf");
            }

            using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature(new Document(dataDir + "externalSignature2.pdf")))
            {
                IList <string> sigNames = pdfSign.GetSignNames();
                for (int index = 0; index <= sigNames.Count - 1; index++)
                {
                    if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
                    {
                        throw new ApplicationException("Not verified");
                    }
                }
            }
            // ExEnd:1
        }
        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;
        } 
Пример #30
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();
            }
        }
Пример #31
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Load PDF document from disk
            String      input = "../../../../../../Data/PDFTemplate_HF.pdf";
            PdfDocument doc   = new PdfDocument();

            doc.LoadFromFile(input);

            //Sign with certificate selection in the windows certificate store
            System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
            store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);

            //Manually chose the certificate in the store
            System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);

            //Create a certificate using the certificate data from the store
            PdfCertificate cert = new PdfCertificate(sel[0].RawData);

            PdfSignature signature = new PdfSignature(doc, doc.Pages[0], cert, "signature0");

            signature.Bounds = new RectangleF(new PointF(250, 660), new SizeF(250, 90));

            //Load sign image source.
            signature.SignImageSource = PdfImage.FromFile("../../../../../../Data/E-iceblueLogo.png");

            //Set the dispay mode of graphics, if not set any, the default one will be applied
            signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
            signature.NameLabel    = "Signer:";

            signature.Name = sel[0].GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

            signature.ContactInfoLabel = "ContactInfo:";
            signature.ContactInfo      = signature.Certificate.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

            signature.DateLabel = "Date:";
            signature.Date      = DateTime.Now;

            signature.LocationInfoLabel = "Location:";
            signature.LocationInfo      = "Chengdu";

            signature.ReasonLabel = "Reason: ";
            signature.Reason      = "The certificate of this document";

            signature.DistinguishedNameLabel = "DN: ";
            signature.DistinguishedName      = signature.Certificate.IssuerName.Name;

            signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
            signature.Certificated        = true;

            //Set fonts, if not set, default ones will be applied
            signature.SignDetailsFont = new PdfFont(PdfFontFamily.TimesRoman, 10f);
            signature.SignNameFont    = new PdfFont(PdfFontFamily.Courier, 15);

            //Set the sign image layout mode
            signature.SignImageLayout = SignImageLayout.None;

            //Save the PDF file
            String output = "SignWithSmartCardUsingPdfFileSignature_out.pdf";

            doc.SaveToFile(output);
            doc.Close();

            //Launch the Pdf file
            PDFDocumentViewer(output);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Load PDF document from disk
            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile("../../../../../../Data/SignatureField.pdf");

            PdfFormWidget widgets = doc.Form as PdfFormWidget;

            for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
            {
                PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;
                if (widget is PdfSignatureFieldWidget)
                {
                    //Get the field name
                    string name = widget.Name;
                    PdfSignatureFieldWidget signWidget = widget as PdfSignatureFieldWidget;

                    //Sign with certificate selection in the windows certificate store
                    System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
                    store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);

                    //Manually chose the certificate in the store
                    System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);

                    //Create a certificate using the certificate data from the store
                    PdfCertificate cert = new PdfCertificate(sel[0].RawData);

                    //Create a signature using the signature field
                    PdfSignature signature = new PdfSignature(doc, signWidget.Page, cert, name, signWidget);

                    //Load sign image source
                    signature.SignImageSource = PdfImage.FromFile("../../../../../../Data/E-iceblueLogo.png");

                    //Set the dispay mode of graphics, if not set any, the default one will be applied
                    signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
                    signature.NameLabel    = "Signer:";

                    signature.Name = sel[0].GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

                    signature.ContactInfoLabel = "ContactInfo:";
                    signature.ContactInfo      = signature.Certificate.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);

                    signature.DateLabel = "Date:";
                    signature.Date      = DateTime.Now;

                    signature.LocationInfoLabel = "Location:";
                    signature.LocationInfo      = "Chengdu";

                    signature.ReasonLabel = "Reason: ";
                    signature.Reason      = "The certificate of this document";

                    signature.DistinguishedNameLabel = "DN: ";
                    signature.DistinguishedName      = signature.Certificate.IssuerName.Name;

                    signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges;
                    signature.Certificated        = true;

                    //Set fonts, if not set, default ones will be applied
                    signature.SignDetailsFont = new PdfFont(PdfFontFamily.TimesRoman, 10f);
                    signature.SignNameFont    = new PdfFont(PdfFontFamily.Courier, 15);

                    //Set the sign image layout mode
                    signature.SignImageLayout = SignImageLayout.None;
                }
            }

            //Save the Pdf document
            string output = "SignWithSmartCardUsingSignatureField_out.pdf";

            doc.SaveToFile(output);

            //Launch the result file
            PDFDocumentViewer(output);
        }