コード例 #1
0
		/// <summary>
		/// Imports certificates and keys from a pkcs12-encoded stream.
		/// </summary>
		/// <remarks>
		/// Imports certificates and keys from a pkcs12-encoded stream.
		/// </remarks>
		/// <param name="stream">The raw certificate and key data.</param>
		/// <param name="password">The password to unlock the stream.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="stream"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="password"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// Importing keys is not supported by this cryptography context.
		/// </exception>
		public override void Import (Stream stream, string password)
		{
			if (stream == null)
				throw new ArgumentNullException ("stream");

			if (password == null)
				throw new ArgumentNullException ("password");

			var rawData = ReadAllBytes (stream);
			var store = new X509Store (StoreName.My, StoreLocation);
			var certs = new X509Certificate2Collection ();

			store.Open (OpenFlags.ReadWrite);
			certs.Import (rawData, password, X509KeyStorageFlags.UserKeySet);
			store.AddRange (certs);
			store.Close ();
		}
コード例 #2
0
        static void Main(string[] args)
        {
            string clusterEndpoint  = "docdb-2021-03-31-11-44-27.cluster-cihrsqslvehp.eu-west-1.docdb.amazonaws.com:27017";
            string template         = "mongodb://{0}:{1}@{2}/sampledatabase?ssl=true&replicaSet=rs0&readpreference={3}";
            string username         = "******";
            string password         = "******";
            string readPreference   = "secondaryPreferred";
            string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);

            string pathToCAFile = "rdscombinedcabundle_cert_out.p7b";

            // ADD CA certificate to local trust store
            // DO this once - Maybe when your service starts
            X509Store localTrustStore = new X509Store(StoreName.Root);
            X509Certificate2Collection certificateCollection = new X509Certificate2Collection();

            certificateCollection.Import(pathToCAFile);
            try
            {
                localTrustStore.Open(OpenFlags.ReadWrite);
                localTrustStore.AddRange(certificateCollection);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Root certificate import failed: " + ex.Message);
                throw;
            }
            finally
            {
                localTrustStore.Close();
            }

            var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
            var client   = new MongoClient(settings);

            var database   = client.GetDatabase("sample_database");
            var collection = database.GetCollection <BsonDocument>("sample_collecion");

            collection.InsertOne(new BsonDocument {
                { "name", "Juan" }, { "age", 34 }
            });
        }
コード例 #3
0
        /// <summary>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </summary>
        /// <remarks>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </remarks>
        /// <param name="stream">The raw certificate and key data.</param>
        /// <param name="password">The password to unlock the stream.</param>
        /// <param name="flags">The storage flags to use when importing the certificate and private key.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        public void Import(Stream stream, string password, X509KeyStorageFlags flags)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            var rawData = ReadAllBytes(stream);
            var store   = new X509Store(StoreName.My, StoreLocation);
            var certs   = new X509Certificate2Collection();

            store.Open(OpenFlags.ReadWrite);
            certs.Import(rawData, password, flags);
            store.AddRange(certs);
            store.Close();
        }
コード例 #4
0
        /// <summary>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </summary>
        /// <remarks>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </remarks>
        /// <param name="stream">The raw certificate and key data.</param>
        /// <param name="password">The password to unlock the stream.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// Importing keys is not supported by this cryptography context.
        /// </exception>
        public override void Import(Stream stream, string password)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            byte[] rawData;

            if (stream is MemoryBlockStream)
            {
                rawData = ((MemoryBlockStream)stream).ToArray();
            }
            else if (stream is MemoryStream)
            {
                rawData = ((MemoryStream)stream).ToArray();
            }
            else
            {
                using (var memory = new MemoryStream()) {
                    stream.CopyTo(memory, 4096);
                    rawData = memory.ToArray();
                }
            }

            var store = new X509Store(StoreName.My, StoreLocation);
            var certs = new X509Certificate2Collection();

            store.Open(OpenFlags.ReadWrite);
            certs.Import(rawData, password, X509KeyStorageFlags.UserKeySet);
            store.AddRange(certs);
            store.Close();
        }
コード例 #5
0
        /// <summary>
        /// Import certificates in the solution trust collection
        /// </summary>
        /// <param name="services"></param>
        public static void ConfigureCertificate(this IServiceCollection services)
        {
            string pathToCAFile = "./CERTIFICATE_NAME.p7b";

            // ADD CA certificate to local trust store
            X509Store localTrustStore = new X509Store(StoreName.Root);
            X509Certificate2Collection certificateCollection = new X509Certificate2Collection();

            try
            {
                certificateCollection.Import(pathToCAFile);
                localTrustStore.Open(OpenFlags.ReadWrite);
                localTrustStore.AddRange(certificateCollection);
            }
            catch (Exception ex)
            {
                Console.Write("Root certificate import failed: " + ex.Message);
            }
            finally
            {
                localTrustStore.Close();
            }
        }
コード例 #6
0
        private static X509Store AddChainCertsToStore(List <string> certificateChainList, int hashCodeForTracing)
        {
            X509Store x509Store = CertificateStore.Open(StoreType.Memory, null, OpenFlags.ReadWrite);

            try
            {
                foreach (string s in certificateChainList)
                {
                    X509Certificate2Collection x509Certificate2Collection = new X509Certificate2Collection();
                    x509Certificate2Collection.Import(Convert.FromBase64String(s));
                    x509Store.AddRange(x509Certificate2Collection);
                }
            }
            catch (SecurityException arg)
            {
                AirSyncDiagnostics.TraceDebug <SecurityException>(ExTraceGlobals.RequestTracer, null, "Failed to add certificates to temporary memory store: '{0}'", arg);
            }
            catch (CryptographicException arg2)
            {
                AirSyncDiagnostics.TraceDebug <CryptographicException>(ExTraceGlobals.RequestTracer, null, "Failed to add certificates to temporary memory store: '{0}'", arg2);
            }
            return(x509Store);
        }
コード例 #7
0
 public void Add(X509Certificate2Collection collection) => _store.AddRange(collection);
コード例 #8
0
        public async Task SslStream_ClientCertificate_SendsChain()
        {
            List <SslStream> streams = new List <SslStream>();

            TestHelper.CleanupCertificates();
            (X509Certificate2 clientCertificate, X509Certificate2Collection clientChain) = TestHelper.GenerateCertificates("SslStream_ClinetCertificate_SendsChain", serverCertificate: false);
            using (X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
            {
                // add chain certificate so we can construct chain since there is no way how to pass intermediates directly.
                store.Open(OpenFlags.ReadWrite);
                store.AddRange(clientChain);
                store.Close();
            }

            using (var chain = new X509Chain())
            {
                chain.ChainPolicy.VerificationFlags           = X509VerificationFlags.AllFlags;
                chain.ChainPolicy.RevocationMode              = X509RevocationMode.NoCheck;
                chain.ChainPolicy.DisableCertificateDownloads = false;
                bool chainStatus = chain.Build(clientCertificate);
                // Verify we can construct full chain
                if (chain.ChainElements.Count < clientChain.Count)
                {
                    throw new SkipTestException($"chain cannot be built {chain.ChainElements.Count}");
                }
            }

            var clientOptions = new  SslClientAuthenticationOptions()
            {
                TargetHost = "localhost",
            };

            clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            clientOptions.LocalCertificateSelectionCallback   = (sender, target, certificates, remoteCertificate, issuers) => clientCertificate;

            var serverOptions = new SslServerAuthenticationOptions()
            {
                ClientCertificateRequired = true
            };

            serverOptions.ServerCertificateContext            = SslStreamCertificateContext.Create(Configuration.Certificates.GetServerCertificate(), null);
            serverOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
            {
                // Client should send chain without root CA. There is no good way how to know if the chain was built from certificates
                // from wire or from system store. However, SslStream adds certificates from wire to ExtraStore in RemoteCertificateValidationCallback.
                // So we verify the operation by checking the ExtraStore. On Windows, that includes leaf itself.
                _output.WriteLine("RemoteCertificateValidationCallback called with {0} and {1} extra certificates", sslPolicyErrors, chain.ChainPolicy.ExtraStore.Count);
                foreach (X509Certificate c in chain.ChainPolicy.ExtraStore)
                {
                    _output.WriteLine("received {0}", c.Subject);
                }

                Assert.True(chain.ChainPolicy.ExtraStore.Count >= clientChain.Count - 1, "client did not sent expected chain");
                return(true);
            };

            // run the test multiple times while holding established SSL so we could hit credential cache.
            for (int i = 0; i < 3; i++)
            {
                (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams();
                SslStream client = new SslStream(clientStream);
                SslStream server = new SslStream(serverStream);

                Task t1 = client.AuthenticateAsClientAsync(clientOptions, CancellationToken.None);
                Task t2 = server.AuthenticateAsServerAsync(serverOptions, CancellationToken.None);
                await Task.WhenAll(t1, t2).WaitAsync(TestConfiguration.PassingTestTimeout);

                // hold to the streams so they stay in credential cache
                streams.Add(client);
                streams.Add(server);
            }

            TestHelper.CleanupCertificates();
            clientCertificate.Dispose();
            foreach (X509Certificate c in clientChain)
            {
                c.Dispose();
            }

            foreach (SslStream s in  streams)
            {
                s.Dispose();
            }
        }
コード例 #9
0
    public static void Main(string[] args)
    {
        //Opens the personal certificates store.
        X509Store store = new X509Store(StoreName.My);

        store.Open(OpenFlags.ReadWrite);
        X509Certificate2 certificate = new X509Certificate2();

        //Create certificates from certificate files.
        //You must put in a valid path to three certificates in the following constructors.
        X509Certificate2 certificate1 = new X509Certificate2("c:\\mycerts\\*****.cer");
        X509Certificate2 certificate2 = new X509Certificate2("c:\\mycerts\\*****.cer");
        X509Certificate2 certificate5 = new X509Certificate2("c:\\mycerts\\*****.cer");

        //Create a collection and add two of the certificates.
        X509Certificate2Collection collection = new X509Certificate2Collection();

        collection.Add(certificate2);
        collection.Add(certificate5);

        //Add certificates to the store.
        store.Add(certificate1);
        store.AddRange(collection);

        X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;

        Console.WriteLine("Store name: {0}", store.Name);
        Console.WriteLine("Store location: {0}", store.Location);
        foreach (X509Certificate2 x509 in storecollection)
        {
            Console.WriteLine("certificate name: {0}", x509.Subject);
        }

        //Remove a certificate.
        store.Remove(certificate1);
        X509Certificate2Collection storecollection2 = (X509Certificate2Collection)store.Certificates;

        Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine);
        foreach (X509Certificate2 x509 in storecollection2)
        {
            Console.WriteLine("certificate name: {0}", x509.Subject);
        }

        //Remove a range of certificates.
        store.RemoveRange(collection);
        X509Certificate2Collection storecollection3 = (X509Certificate2Collection)store.Certificates;

        Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine);
        if (storecollection3.Count == 0)
        {
            Console.WriteLine("Store contains no certificates.");
        }
        else
        {
            foreach (X509Certificate2 x509 in storecollection3)
            {
                Console.WriteLine("certificate name: {0}", x509.Subject);
            }
        }

        //Close the store.
        store.Close();
    }
コード例 #10
0
        private X509Certificate2 FindBestCert(IEnumerable <string> emails, bool isContact, params byte[][][] paramsCertsRawData)
        {
            X509Certificate2 result;

            try
            {
                X509CertificateCollection x509CertificateCollection = new X509CertificateCollection();
                foreach (byte[][] array in paramsCertsRawData)
                {
                    if (array != null)
                    {
                        foreach (byte[] array3 in array)
                        {
                            try
                            {
                                if (isContact)
                                {
                                    x509CertificateCollection.ImportFromContact(array3);
                                }
                                else
                                {
                                    x509CertificateCollection.Import(array3);
                                }
                            }
                            catch (Exception ex)
                            {
                                this.LogException(ex, "Error occurred when parsing cert raw data {0}", new object[]
                                {
                                    Convert.ToBase64String(array3)
                                });
                            }
                        }
                    }
                }
                X509Store x509Store = null;
                if (!string.IsNullOrEmpty(this.smimeAdminOptions.SMIMECertificateIssuingCAFull))
                {
                    x509Store = CertificateStore.Open(StoreType.Memory, null, OpenFlags.ReadWrite);
                    X509Certificate2Collection x509Certificate2Collection = new X509Certificate2Collection();
                    x509Certificate2Collection.Import(Convert.FromBase64String(this.smimeAdminOptions.SMIMECertificateIssuingCAFull));
                    x509Store.AddRange(x509Certificate2Collection);
                }
                result = x509CertificateCollection.FindSMimeCertificate(emails, X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment, false, TimeSpan.FromMilliseconds(this.smimeAdminOptions.CRLConnectionTimeout), TimeSpan.FromMilliseconds(this.smimeAdminOptions.CRLRetrievalTimeout), x509Store, base.CallContext.AccessingPrincipal.MailboxInfo.OrganizationId.ToString());
            }
            catch (Exception ex2)
            {
                StringBuilder stringBuilder = new StringBuilder();
                foreach (byte[][] array4 in paramsCertsRawData)
                {
                    if (array4 != null)
                    {
                        foreach (byte[] array6 in array4)
                        {
                            if (array6 != null)
                            {
                                stringBuilder.AppendLine(Convert.ToBase64String(array6));
                            }
                        }
                    }
                }
                this.LogException(ex2, "Error occurred when finding best cert from: {0}", new object[]
                {
                    stringBuilder
                });
                result = null;
            }
            return(result);
        }
コード例 #11
0
	static void AddCertificatesToStore(string cert , string password , StoreLocation loc)
		{
		//Import the pfx certificates
		X509Certificate2Collection certificates = new X509Certificate2Collection() ; 
		certificates.Import( cert , password , X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
		
		//Add the Certificate
		X509Store store = new X509Store( storeName , loc) ; // , "Cool Store" ) ; 
		store.Open( OpenFlags.ReadWrite ) ;
		store.AddRange( certificates ) ; 			
		store.Close() ; 
		}
コード例 #12
0
        private static void Sample2()
        {
            //Create new X509 store called teststore from the local certificate store.
            X509Store store = new X509Store("teststore", StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadWrite);

            //Create certificates from certificate files.
            //You must put in a valid path to three certificates in the following constructors.
            X509Certificate2 certificate1 = new X509Certificate2("c:\\mycerts\\*****.cer");
            X509Certificate2 certificate2 = new X509Certificate2("c:\\mycerts\\*****.cer");
            X509Certificate2 certificate5 = new X509Certificate2("c:\\mycerts\\*****.cer");

            //Create a collection and add two of the certificates.
            X509Certificate2Collection collection = new X509Certificate2Collection
            {
                certificate2,
                certificate5
            };

            //Add certificates to the store.
            store.Add(certificate1);
            store.AddRange(collection);

            X509Certificate2Collection storecollection = store.Certificates;

            Console.WriteLine("Store name: {0}", store.Name);
            Console.WriteLine("Store location: {0}", store.Location);
            foreach (X509Certificate2 x509 in storecollection)
            {
                Console.WriteLine("certificate name: {0}", x509.Subject);
            }

            //Remove a certificate.
            store.Remove(certificate1);
            X509Certificate2Collection storecollection2 = store.Certificates;

            Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine);
            foreach (X509Certificate2 x509 in storecollection2)
            {
                Console.WriteLine("certificate name: {0}", x509.Subject);
            }

            //Remove a range of certificates.
            store.RemoveRange(collection);
            X509Certificate2Collection storecollection3 = store.Certificates;

            Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine);
            if (storecollection3.Count == 0)
            {
                Console.WriteLine("Store contains no certificates.");
            }
            else
            {
                foreach (X509Certificate2 x509 in storecollection3)
                {
                    Console.WriteLine("certificate name: {0}", x509.Subject);
                }
            }

            //Close the store.
            store.Close();
        }
コード例 #13
0
        public async Task MultiCertsTest()
        {
            if (!String.IsNullOrEmpty(_fixture.GetCertsFilePath()))
            {
                var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadWrite);
                var certs = new X509Certificate2Collection();

#if NET5_0_OR_GREATER
                certs.ImportFromPemFile(_fixture.GetCertsFilePath());
#else
                const string endCert      = "-----END CERTIFICATE-----";
                var          certFileText = File.ReadAllText(_fixture.GetCertsFilePath());
                var          certStrings  = certFileText.Split(endCert, StringSplitOptions.RemoveEmptyEntries);
                foreach (var certString in certStrings)
                {
                    if (certString.Contains("BEGIN CERTIFICATE"))
                    {
                        var bytes = Encoding.Default.GetBytes(certString + endCert);
                        var cert  = new X509Certificate2(bytes);
                        certs.Add(cert);
                    }
                }
#endif
                store.AddRange(certs);
                var findByValue = store.Certificates[0].Thumbprint;

                // Find certificates in local store
                _fixture.GetClusterOptions().X509CertificateFactory = CertificateFactory.GetCertificatesFromStore(
                    new CertificateStoreSearchCriteria()
                {
                    StoreLocation = StoreLocation.CurrentUser,
                    StoreName     = StoreName.My,
                    X509FindType  = X509FindType.FindByThumbprint,
                    FindValue     = findByValue
                });;

                var cluster = await Cluster.ConnectAsync(_fixture.GetClusterOptions().ConnectionString, _fixture.GetClusterOptions());

                await cluster.WaitUntilReadyAsync(TimeSpan.FromSeconds(10));

                var bucket = await cluster.BucketAsync("default");

                var key = Guid.NewGuid().ToString();

                try
                {
                    await bucket.DefaultCollection().UpsertAsync(key, "Multicerts test data");

                    var result = await bucket.DefaultCollection().GetAsync(key);

                    Assert.Equal("Multicerts test data", (string)result.ContentAs <dynamic>());
                }
                finally
                {
                    await bucket.DefaultCollection().RemoveAsync(key);
                }

                store.RemoveRange(certs);
                store.Close();
            }
        }
コード例 #14
0
        public string Post([FromBody] Models.ModeloS3 data)
        {
            AmazonBatchClient batchClient = new AmazonBatchClient();

            SubmitJobResponse submitJobResponse1 = batchClient.SubmitJobAsync(new SubmitJobRequest()
            {
                ContainerOverrides = new ContainerOverrides() //opciones de contenedor
                {
                    Command = new List <string>()
                    {
                        data.bucket, data.key
                    }                                 //input del contenedor
                },
                JobDefinition = "formacionBatch",     //definicion de trabajo
                JobName       = "trabajo-webservice", //nombre del trabajo
                JobQueue      = "formacionBatch",     //cola de trabajo
            }).Result;

            string clusterEndpoint  = "docdb-2021-03-31-11-44-27.cluster-cihrsqslvehp.eu-west-1.docdb.amazonaws.com:27017";
            string template         = "mongodb://{0}:{1}@{2}/sampledatabase?ssl=true&replicaSet=rs0&readpreference={3}";
            string username         = "******";
            string password         = "******";
            string readPreference   = "secondaryPreferred";
            string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);

            string pathToCAFile = "rdscombinedcabundle_cert_out.p7b";

            // ADD CA certificate to local trust store
            // DO this once - Maybe when your service starts
            X509Store localTrustStore = new X509Store(StoreName.Root);
            X509Certificate2Collection certificateCollection = new X509Certificate2Collection();

            certificateCollection.Import(pathToCAFile);
            try
            {
                localTrustStore.Open(OpenFlags.ReadWrite);
                localTrustStore.AddRange(certificateCollection);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Root certificate import failed: " + ex.Message);
                throw;
            }
            finally
            {
                localTrustStore.Close();
            }

            var settings   = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
            var client     = new MongoClient(settings);
            var database   = client.GetDatabase("sample_database");
            var collection = database.GetCollection <BsonDocument>("tracking");

            collection.InsertOne(new BsonDocument
            {
                { "ip", HttpContext.Connection.RemoteIpAddress.ToString() },
                { "fecha", DateTime.Now },
                { "bucket", data.bucket },
                { "key", data.key },
            });

            return("Trabajo enviado");
        }