예제 #1
0
        private void bGenerateCertificate_Click(object sender, EventArgs e)
        {
            X509Certificate cert = new X509Certificate(Encoding.UTF8.GetBytes(tbBinaryData.Text));

            byte[]          certData = cert.Export(X509ContentType.Cert);
            X509Certificate newCert  = new X509Certificate(certData);

            File.WriteAllBytes(filePath, cert.Export(X509ContentType.Cert));
            tbResult.Text = filePath + " created!";
        }
예제 #2
0
파일: SslListener.cs 프로젝트: Ultz/Spirit
        public SslListener(IHttpListener child, X509Certificate certificate)
        {
            _child = child;
#if NETCOREAPP2_1 || NETSTANDARD2_1
            _auth = new SslServerAuthenticationOptions()
            {
                ServerCertificate         = new X509Certificate2(certificate.Export(X509ContentType.Pkcs12)),
                ClientCertificateRequired = false,
                EnabledSslProtocols       = SslProtocols.Tls12
            };
#else
            _certificate = new X509Certificate2(certificate.Export(X509ContentType.Pkcs12));
#endif
        }
        /// <summary>
        /// Converts a <see cref="X509Certificate"/> (or an object that can be cast to an <see cref="X509Certificate"/>) to a specified type.
        /// </summary>
        /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">A <see cref="CultureInfo"/> that holds information about a specific culture.</param>
        /// <param name="value">The object to convert. This object should be of type <see cref="X509Certificate"/> or some type that can be cast to <see cref="X509Certificate"/>.</param>
        /// <param name="destinationType">The <see cref="Type"/> to convert the <see cref="X509Certificate"/> to.</param>
        /// <returns>If this method succeeds, it returns the converted object. Otherwise, it throws an exception.</returns>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }
            if (destinationType == typeof(string))
            {
                return((value != null) ? value.ToString() : "(none)");
            }
            if (destinationType != typeof(byte[]))
            {
                return(base.ConvertTo(context, culture, value, destinationType));
            }
            if (value == null)
            {
                return(new byte[0]);
            }
            X509Certificate cert = value as X509Certificate;

            if (cert != null)
            {
                return(cert.Export(X509ContentType.Cert));
            }
            return(null);
        }
예제 #4
0
        /// <summary>
        /// Function will create and export certificate to PKCS12 format (PFX) with password (if any)
        /// </summary>
        /// <param name="keyContainerName">Name of the key container.</param>
        /// <param name="cspProvider">The CSP provider.</param>
        /// <param name="keySpec">The key specification</param>
        /// <param name="cspFlags">The CSP flags.</param>
        /// <param name="pfxPassword">The PFX password.</param>
        /// <returns>Certificate exported to PKCS#12 format and converted to bytes</returns>
        internal byte[] ExportCertToPKCS12(String keyContainerName, String cspProvider = MS_DEF_PROV, uint keySpec = AT_KEYEXCHANGE, uint cspFlags = 0, string pfxPassword = "")
        {
            byte[] pfxblob    = null;
            IntPtr hCertCntxt = IntPtr.Zero;

            String DN = "CN=Opensslkey Unsigned Certificate";

            hCertCntxt = CreateUnsignedCertCntxt(keyContainerName, DN, cspProvider, keySpec, cspFlags);
            if (hCertCntxt == IntPtr.Zero)
            {
                throw new ApplicationException("Could not create certificate");
            }

            try
            {
                X509Certificate cert = new X509Certificate(hCertCntxt); //create certificate object from cert context.
                //X509Certificate2UI.DisplayCertificate(new X509Certificate2(cert));	// display it, showing linked private key
                pfxblob = cert.Export(X509ContentType.Pkcs12, pfxPassword);
            }
            catch (Exception exc)
            {
                throw new ApplicationException("Could not create certificate. Message: " + exc.Message, exc);
            }

            if (hCertCntxt != IntPtr.Zero)
            {
                UnsafeNativeMethods.CertFreeCertificateContext(hCertCntxt);
            }

            return(pfxblob);
        }
예제 #5
0
        //------   Since we are using an RSA with nonpersisted keycontainer, must pass it in to ensure it isn't colledted  -----
        private static byte[] GetPkcs12(RSA rsa, String keycontainer, String cspprovider, uint KEYSPEC, uint cspflags)
        {
            byte[] pfxblob    = null;
            IntPtr hCertCntxt = IntPtr.Zero;

            String DN = "CN=Opensslkey Unsigned Certificate";

            hCertCntxt = CreateUnsignedCertCntxt(keycontainer, cspprovider, KEYSPEC, cspflags, DN);
            if (hCertCntxt == IntPtr.Zero)
            {
                Console.WriteLine("Couldn't create an unsigned-cert\n");
                return(null);
            }
            try
            {
                X509Certificate cert = new X509Certificate(hCertCntxt); //create certificate object from cert context.
                SecureString    pswd = GetSecPswd("Set PFX ==>");
                pfxblob = cert.Export(X509ContentType.Pkcs12, pswd);
            }

            catch (Exception exc)
            {
                Console.WriteLine("BAD RESULT" + exc.Message);
                pfxblob = null;
            }

            rsa.Clear();
            if (hCertCntxt != IntPtr.Zero)
            {
                Win32.CertFreeCertificateContext(hCertCntxt);
            }
            return(pfxblob);
        }
    public static bool RemoteServerCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return(true);
        }
        // if got an cert auth error
        if (sslPolicyErrors != SslPolicyErrors.RemoteCertificateNameMismatch)
        {
            return(false);
        }
        const string sertFileName = "smpthost.cer";

        // check if cert file exists
        if (File.Exists(sertFileName))
        {
            var actualCertificate = X509Certificate.CreateFromCertFile(sertFileName);
            return(certificate.Equals(actualCertificate));
        }
        // export and check if cert not exists
        using (var file = File.Create(sertFileName))
        {
            var cert = certificate.Export(X509ContentType.Cert);
            file.Write(cert, 0, cert.Length);
        }
        var createdCertificate = X509Certificate.CreateFromCertFile(sertFileName);

        return(certificate.Equals(createdCertificate));
    }
        private async Task StartMqttServer()
        {
            // Start a MQTT server.
            Logger.LogInfo(LogCategory.Processor, this.Name, "Starting MQTT Server..");

            _mqttServer = new MqttFactory().CreateMqttServer();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(BrokerPort)
                                 .WithConnectionValidator(AuthenticateUser)
                                 .WithStorage(new RetainedMqttMessageHandler());

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(EncryptedBrokerPort);
            }

            var options = optionsBuilder.Build();

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                var certificate = new X509Certificate(SecureCommunicationCertLocation, "");
                options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            }

            await _mqttServer.StartAsync(options);
        }
예제 #8
0
 public void UpdateCertificate(X509Certificate cert)
 {
     _updateCertificate.UpdateCertificate(cert);
     File.WriteAllBytes(CertPathOnDisk, cert.Export(X509ContentType.Pfx, CertPassword));
     _lastUpdate = DateTime.UtcNow;
     LogInfo("Certificate successfully updated");
 }
예제 #9
0
        public static async Task <IMqttClient> ConnectAsync(string clientId)
        {
            Console.WriteLine("In ConnectAsync");
            var             client = new MqttFactory().CreateMqttClient();
            X509Certificate ca_crt = new X509Certificate("certs/ca.crt");

            var tlsOptions = new MqttClientOptionsBuilderTlsParameters();

            tlsOptions.SslProtocol  = System.Security.Authentication.SslProtocols.Tls11;
            tlsOptions.Certificates = new List <IEnumerable <byte> >()
            {
                ca_crt.Export(X509ContentType.Cert).Cast <byte>()
            };
            tlsOptions.UseTls = true;
            tlsOptions.AllowUntrustedCertificates        = true;
            tlsOptions.IgnoreCertificateChainErrors      = false;
            tlsOptions.IgnoreCertificateRevocationErrors = false;

            Console.WriteLine("MQTT_BROKER_ADDRESS: {0}", MQTT_BROKER_ADDRESS);
            Console.WriteLine("MQTT_BROKER_PORT: {0}", MQTT_BROKER_PORT);

            // TLS support on port 4321 (8883 already in use with Azure IoT Edge)
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(clientId)
                          .WithTcpServer(MQTT_BROKER_ADDRESS, MQTT_BROKER_PORT)
                          .WithTls(tlsOptions)
                          .Build();

            await client.ConnectAsync(options);

            return(client);
        }
예제 #10
0
        private static void Usingcertificate(ref MqttServerOptions options)
        {
            var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");

            options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            var aes = new System.Security.Cryptography.AesManaged();
        }
예제 #11
0
        public static IServiceCollection AddMqtt(this IServiceCollection services)
        {
            IMqttService mqttService = new MqttService();

            services.AddSingleton <IMqttService>(mqttService);

            var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");

            var options = new MqttServerOptionsBuilder()
                          .WithConnectionValidator(mqttService.ValidateConnection)
                          .WithApplicationMessageInterceptor(mqttService.InterceptApplicationMessage)
                          .WithSubscriptionInterceptor(mqttService.InterceptSubscription)
                          .WithEncryptionCertificate(certificate.Export(X509ContentType.Cert))
                          .Build();

            services.AddSingleton(options);
            services.AddSingleton <IMqttNetLogger>(new MqttNetLogger());
            services.AddSingleton <MqttHostedServer>();
            services.AddSingleton <IHostedService>(s => s.GetService <MqttHostedServer>());
            services.AddSingleton <IMqttServer>(s => s.GetService <MqttHostedServer>());

            services.AddSingleton <MqttWebSocketServerAdapter>();
            services.AddSingleton <MqttServerAdapter>();
            services.AddSingleton <IEnumerable <IMqttServerAdapter> >(s =>
            {
                List <IMqttServerAdapter> adapters = new List <IMqttServerAdapter>();
                adapters.Add(s.GetService <MqttServerAdapter>());
                adapters.Add(s.GetService <MqttWebSocketServerAdapter>());
                return(adapters);
            });

            return(services);
        }
예제 #12
0
        static void ConvertCerToPfx(string pathCer, string pathPfx, string password)
        {
            string msg = String.Empty;

            try
            {
                if (!String.IsNullOrEmpty(pathCer) && !String.IsNullOrEmpty(pathPfx) && !String.IsNullOrEmpty(password))
                {
                    X509Certificate cert     = new X509Certificate(pathCer);
                    byte[]          certData = cert.Export(X509ContentType.Pkcs12, password);

                    File.WriteAllBytes(pathPfx, certData);
                    msg = "Certificado convertido com sucesso.";
                }
                else
                {
                    msg = String.Format("Falha ao converter Certificado:{0}Parametros inválidos.", Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                msg = String.Format("Falha ao converter Certificado: ", Environment.NewLine);
            }

            Console.Write(msg);
            Console.ReadLine();
        }
예제 #13
0
        internal bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (_cert != null)
            {
                X509Certificate2 ca = _cert.Value;

                using (X509Chain chain2 = new X509Chain())
                {
                    chain2.ChainPolicy.ExtraStore.Add(ca);
                    chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                    chain2.ChainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
                    chain2.ChainPolicy.RevocationFlag    = X509RevocationFlag.EndCertificateOnly;

                    X509Certificate2 cert = new X509Certificate2(certificate.Export(X509ContentType.Cert));

                    //AllowUnknownCertificateAuthority 无法解决 UntrustedRoot 问题。
                    //https://stackoverflow.com/questions/27307322/verify-server-certificate-against-self-signed-certificate-authority?rq=1
                    if (chain2.Build(cert))
                    {
                        var chainThumbprint = chain2.ChainElements[chain2.ChainElements.Count - 1].Certificate.Thumbprint;
                        return(chainThumbprint == ca.Thumbprint); // success?
                    }
                    return(false);
                    //return (chain2.ChainStatus.Length == 0 || chain2.ChainStatus[0].Status == X509ChainStatusFlags.NoError);
                }
            }

            return(chain.ChainStatus.Length == 0 || chain.ChainStatus[0].Status == X509ChainStatusFlags.NoError);
        }
예제 #14
0
        static void websign(string[] args)
        {
            digidoc.digidoc.initialize();
            try
            {
                Console.WriteLine("Creating file: " + args[args.Length - 1]);
                Container b = Container.create(args[args.Length - 1]);
                for (int i = 1; i < args.Length - 2; ++i)
                {
                    b.addDataFile(args[i], "application/octet-stream");
                }

                X509Certificate cert = new X509Certificate();
                cert.Import(args[args.Length - 2]);
                Signature c = b.prepareWebSignature(cert.Export(X509ContentType.Cert), "BES/time-stamp");
                Console.WriteLine("Signature method: " + c.signatureMethod());
                Console.WriteLine("Digest to sign: " + BitConverter.ToString(c.dataToSign()).Replace("-", string.Empty));
                Console.WriteLine("Please enter signed digest in hex: ");

                byte[] inputBuffer = new byte[1024];
                Stream inputStream = Console.OpenStandardInput(inputBuffer.Length);
                Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length));
                String hex = Console.ReadLine();

                byte[] signature = Enumerable.Range(0, hex.Length / 2).Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16)).ToArray();
                c.setSignatureValue(signature);
                c.extendSignatureProfile("BES/time-stamp");
                b.save();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            digidoc.digidoc.terminate();
        }
예제 #15
0
        public void TestPaddingNewline()
        {
            string expected = "MIICqjCCAjGgAwIBAgICI1YwCQYHKoZIzj0EATAmMSQwIgYDVQQDDBtUcnVzdGVkIFRoaW4gQ2xp\n" +
                              "ZW50IFJvb3QgQ0EwIhcRMTYwMTI0MTU0OTQ1LTA2MDAXDTE2MDQyNTIyNDk0NVowYzEwMC4GA1UE\n" +
                              "AwwnREMgMGRlYzI0MGYtOTI2OS00MDY5LWE2MTYtYjJmNTI0ZjA2ZGE0MREwDwYDVQQLDAhEQyBJ\n" +
                              "UFNFQzEcMBoGA1UECgwTVHJ1c3RlZCBUaGluIENsaWVudDB2MBAGByqGSM49AgEGBSuBBAAiA2IA\n" +
                              "BOB7pZYC24sF5gJmOHXhasxmrNYebdtSAiQRgz0M0pIsogsFeTU/W0HTlTOqwDDckphHESAKHVxa\n" +
                              "6EBLd+/8HYZ1AaCmXtG73XpaOyaRr3TipJl2IaJzwuehgDHs0L+qcqOB8TCB7jAwBgYrBgEBEAQE\n" +
                              "JgwkMGRlYzI0MGYtOTI2OS00MDY5LWE2MTYtYjJmNTI0ZjA2ZGE0MCMGCisGAQQBjCHbZwEEFQwT\n" +
                              "NDkwNzUyMjc1NjM3MTE3Mjg5NjAUBgorBgEEAYwh22cCBAYMBDIwNTkwCwYDVR0PBAQDAgXgMAkG\n" +
                              "A1UdEwQCMAAwHQYDVR0OBBYEFGWljaKjwiGqW61PgLL/zLxj4iirMB8GA1UdIwQYMBaAFA2FRBtG\n" +
                              "/dGnl0iXP2uKFwJHmEQIMCcGA1UdJQQgMB4GCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwkw\n" +
                              "CQYHKoZIzj0EAQNoADBlAjAQFP8rMLUxl36u8610LsSCiRG8pP3gjuLaaJMm3tjbVue/TI4Cz3iL\n" +
                              "8i96YWK0VxcCMQC7pf6Wk3RhUU2Sg6S9e6CiirFLDyzLkaWxuCnXcOwTvuXTHUQSeUCp2Q6ygS5q\n" +
                              "Kyc=";

            string certString = "-----BEGIN CERTIFICATE-----\n" +
                                expected + "\n" +
                                "-----END CERTIFICATE-----";

            X509Certificate cert            = FromString(certString);
            IByteBuffer     src             = Unpooled.WrappedBuffer(cert.Export(X509ContentType.Cert));
            IByteBuffer     expectedEncoded = Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes(expected));

            this.TestEncode(src, expectedEncoded);
        }
예제 #16
0
        public bool ValidateServerCertficate(object sender, X509Certificate receivedCertificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (originalServerCertificate == null)
            {
                return(false);
            }
            else
            {
                if (receivedCertificate.Subject.IndexOf(".xamarin.com", 0, StringComparison.CurrentCultureIgnoreCase) == -1)                   //not a call to an Xamarin server so verify certificate

                {
                    if (originalServerCertificate.Equals(receivedCertificate))
                    {
                        return(true);
                    }
                    else
                    {
                        //incorrect certificate found so notify user
                        CertificateHelper.BytesOfServerCertificate = receivedCertificate.Export(X509ContentType.Cert);

                        EventHandler handler = CertificateMismatchFound;
                        if (handler != null)
                        {
                            handler(this, null);
                        }
                        return(false);
                    }
                }
                else
                {
                    //Call to Xamarin (used for Xamarin.Insights) so accept
                    return(true);
                }
            }
        }
예제 #17
0
        private void wMRootCertificateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = @"Security Certificate|*.crt;*.cer";

            if (DialogResult.OK != openFileDialog.ShowDialog(this))
            {
                return;
            }

            byte[] content;

            try
            {
                var certificate = new X509Certificate(openFileDialog.FileName);
                content = certificate.Export(X509ContentType.Cert);
            }
            catch (CryptographicException)
            {
                MessageBox.Show(this, Resources.WrongData, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            _content = content;

            ToEnabled();
            signStringToolStripMenuItem.Enabled = false;
            SetText();
            SendText(Resources.FileOpened);
        }
예제 #18
0
    public static void Main()
    {
        // The path to the certificate.
        string Certificate = "test.pfx";

        // Load the certificate into an X509Certificate object.
        X509Certificate cert = new X509Certificate(Certificate);


        byte[] certData = cert.Export(X509ContentType.Cert);

        X509Certificate newCert = new X509Certificate(certData);

        // Get the value.
        string resultsTrue = newCert.ToString(true);

        // Display the value to the console.
        Console.WriteLine(resultsTrue);

        // Get the value.
        string resultsFalse = newCert.ToString(false);

        // Display the value to the console.
        Console.WriteLine(resultsFalse);
    }
예제 #19
0
        private void ConvertCerToPfx(string cer, string pfx)
        {
            X509Certificate cert = new X509Certificate(cer);

            byte[] certData = cert.Export(X509ContentType.Pkcs12, "!cbiatwt2");

            System.IO.File.WriteAllBytes(pfx, certData);
        }
        public string ExportarCertificadoPem(string pathCertificado)
        {
            X509Certificate cert      = X509Certificate.CreateFromCertFile(pathCertificado);
            string          contenido = Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks);
            string          pem       = FormatoPEMCertificado(contenido, new StringBuilder());

            return(pem);
        }
예제 #21
0
 private static X509Certificate2 to2(X509Certificate certificate)
 {
                 #if DOTNETCORE
     return(new X509Certificate2(certificate.Export(X509ContentType.Cert)));
                 #else
     return(new X509Certificate2(certificate));
                 #endif
 }
예제 #22
0
        private async Task StartMqttServer()
        {
            // Start a MQTT server.
            Logger.LogInfo(LogCategory.Processor, this.Name, "Starting MQTT Server..");

            _mqttServer = new MqttFactory().CreateMqttServer();

            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 .WithDefaultEndpointPort(BrokerPort)
                                 .WithConnectionValidator(AuthenticateUser)
                                 .WithStorage(new RetainedMqttMessageHandler());

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                optionsBuilder.WithEncryptedEndpoint().WithEncryptedEndpointPort(EncryptedBrokerPort);
            }

            var options = optionsBuilder.Build();

            if (!string.IsNullOrEmpty(SecureCommunicationCertLocation))
            {
                var certificate = new X509Certificate(SecureCommunicationCertLocation, "");
                options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            }

            _mqttServer.Started += (s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Started", a.ToJSON());
            };

            _mqttServer.ApplicationMessageReceived += async(s, a) =>
            {
                Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Server Received Message", a.ToJSON());
            };

            _mqttServer.ClientSubscribedTopic += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Subscribed to Topic", a.ToJSON());
            };

            _mqttServer.ClientUnsubscribedTopic += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Unsubscribed to Topic", a.ToJSON());
            };

            _mqttServer.ClientConnected += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Connected", a.ToJSON());
            };

            _mqttServer.ClientDisconnected += async(s, a) =>
            {
                //Logger.LogTrace(LogCategory.Processor, this.Name, "MQTT Client Disconnected", a.ToJSON());
            };

            await _mqttServer.StartAsync(options);
        }
        /// <summary>
        /// Export a certificate to a PEM format string
        /// </summary>
        /// <param name="certificate">The certificate to export</param>
        /// <returns>A PEM encoded string</returns>
        public string ExportToPEM(X509Certificate certificate)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("-----BEGIN CERTIFICATE-----");
            builder.AppendLine(Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
            builder.AppendLine("-----END CERTIFICATE-----");
            return(builder.ToString());
        }
예제 #24
0
 /// <summary>Export a given certificate</summary>
 private void ExportToPEM(X509Certificate cert, TextWriter target)
 {
     target.WriteLine(BEGIN_CERT);
     target.WriteLine(Convert.ToBase64String(
                          cert.Export(X509ContentType.Cert),
                          Base64FormattingOptions.InsertLineBreaks)
                      );
     target.WriteLine(END_CERT);
 }
예제 #25
0
        async private static void CreateServer()
        {
            string ipAddress = config["mqttSettings:ipaddress"];
            int    port      = Convert.ToInt32(config["mqttSettings:port"]);
            bool   useSSL    = Convert.ToBoolean(config["mqttSettings:useSSL"]);

            // Setup client validator.
            var optionsBuilder = new MqttServerOptionsBuilder()
                                 .WithConnectionBacklog(100)
                                 // .WithDefaultEndpointBoundIPAddress(IPAddress.Parse(ipAddress))
                                 .WithDefaultEndpointPort(port);

            var options = optionsBuilder.Build() as MqttServerOptions;

            //options.ConnectionValidator = c =>
            //{
            //    ConnectionValidator.ValidateConnection(c);
            //};

            if (useSSL)
            {
                string                     certificateName = config["mqttSettings:certificateName"];
                X509Certificate            cert            = null;
                X509Store                  store           = new X509Store(StoreLocation.LocalMachine);
                X509Certificate2Collection cers            = store.Certificates.Find(X509FindType.FindBySubjectName, certificateName, true);
                if (cers.Count > 0)
                {
                    cert = cers[0];
                }
                ;
                options.TlsEndpointOptions.Certificate = cert.Export(X509ContentType.Cert);
            }

            mqttServer = new MqttFactory().CreateMqttServer();
            mqttServer.ClientConnected            += OnConnected;
            mqttServer.ClientDisconnected         += OnDisonnected;
            mqttServer.ClientSubscribedTopic      += OnSubscribe;
            mqttServer.ClientUnsubscribedTopic    += OnUnsubscribe;
            mqttServer.ApplicationMessageReceived += OnMessage;

            MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
            {
                var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                if (e.TraceMessage.Exception != null)
                {
                    trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                }

                Console.WriteLine(trace);
            };

            await mqttServer.StartAsync(options);

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
            //await mqttServer.StopAsync();
        }
예제 #26
0
        /// <summary>
        /// Export a certificate to a PEM format string
        /// </summary>
        /// <param name="cert">The certificate to export</param>
        /// <returns>A PEM encoded string</returns>
        public static string ExportToPEM(this X509Certificate cert)
        {
            StringWriter swriter = new StringWriter();
            PemWriter    writer  = new PemWriter(swriter);

            writer.WriteObject(new X509.X509CertificateParser().ReadCertificate(cert.Export(X509ContentType.Cert)));

            return(swriter.ToString());
        }
        /// <summary>
        /// Export a certificate to a PEM format string
        /// </summary>
        /// <param name="fullCertificate">The full certificate with the private key</param>
        /// <returns>A public certificate</returns>
        public X509Certificate2 GetPublicCertificate(X509Certificate fullCertificate)
        {
            if (fullCertificate is null)
            {
                return(null);
            }
            X509Certificate2 publicCertificate = new X509Certificate2(fullCertificate.Export(X509ContentType.Cert));

            return(publicCertificate);
        }
        public bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            var provided = new X509Certificate2(certificate.Export(X509ContentType.Cert)).Thumbprint;

            if (provided == expectedThumbprint)
            {
                return(true);
            }

            throw new AuthenticationException(string.Format("The server presented an unexpected security certificate. We expected the server to present a certificate with the thumbprint '{0}'. Instead, it presented a certificate with a thumbprint of '{1}'. This usually happens when the client has been configured to expect the server to have the wrong certificate, or when the certificate on the server has been regenerated and the client has not been updated. It may also happen if someone is performing a man-in-the-middle attack on the remote machine, or if a proxy server is intercepting requests. Please check the certificate used on the server, and verify that the client has been configured correctly.", expectedThumbprint, provided));
        }
예제 #29
0
            /// <summary>
            /// Export the public portion of a certificate to a PEM string.
            /// </summary>
            /// <param name="cert"></param>
            /// <returns></returns>
            public static string ExportCertificateToPEM(X509Certificate cert)
            {
                StringBuilder builder = new StringBuilder();

                builder.AppendLine("-----BEGIN CERTIFICATE-----");
                //specify X509ContentType.Cert to get only the public key
                builder.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
                builder.Append("-----END CERTIFICATE-----");

                return(builder.ToString());
            }
예제 #30
0
 public void ExportCaPfx(X509Certificate rootCert, string filePath, string keyPassword)
 {
     //bool exported = false;
     try
     {
         byte[] certData = rootCert.Export(X509ContentType.Pfx, keyPassword);
         System.IO.File.WriteAllBytes(filePath, certData);
         //exported = true;
     }
     catch { }
     //return exported;
 }
예제 #31
0
		//------   Since we are using an RSA with nonpersisted keycontainer, must pass it in to ensure it isn't colledted  -----
		private static byte[] GetPkcs12(RSACryptoServiceProvider rsa, String keycontainer, String cspprovider, uint KEYSPEC, uint cspflags) {
			byte[] pfxblob = null;
			IntPtr hCertCntxt = IntPtr.Zero;

			String DN = "CN=Opensslkey Unsigned Certificate";

			hCertCntxt = CreateUnsignedCertCntxt(keycontainer, cspprovider, KEYSPEC, cspflags, DN);
			if (hCertCntxt == IntPtr.Zero) {
				Console.WriteLine("Couldn't create an unsigned-cert\n");
				return null;
			}
			try {
				X509Certificate cert = new X509Certificate(hCertCntxt);	//create certificate object from cert context.
				// X509Certificate2UI.DisplayCertificate(new X509Certificate2(cert));	// display it, showing linked private key
				SecureString pswd = GetSecPswd("Set PFX Password ==>");
				pfxblob = cert.Export(X509ContentType.Pkcs12, pswd);
			} catch (Exception exc) {
				Console.WriteLine("BAD RESULT" + exc.Message);
				pfxblob = null;
			}

			//rsa.Clear();
			if (hCertCntxt != IntPtr.Zero)
				Win32.CertFreeCertificateContext(hCertCntxt);

			return pfxblob;
		}