Esempio n. 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TTLSSocket"/> class.
 /// </summary>
 /// <param name="host">The host, where the socket should connect to.</param>
 /// <param name="port">The port.</param>
 /// <param name="certificatePath">The certificate path.</param>
 /// <param name="certValidator">User defined cert validator.</param>
 /// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
 public TTLSSocket(
     string host,
     int port,
     string certificatePath,
     RemoteCertificateValidationCallback certValidator = null,
     LocalCertificateSelectionCallback localCertificateSelectionCallback = null)
     : this(host, port, 0, X509Certificate.CreateFromCertFile(certificatePath), certValidator, localCertificateSelectionCallback)
 {
 }
Esempio n. 2
0
        public static void Main()
        {
            // Create a WebRequest that authenticates the user with a
            // username and password combination over Basic authentication.
            WebRequest requestA = WebRequest.Create("http://www.somesite.com");

            requestA.Credentials     = new NetworkCredential("userName", "password");
            requestA.PreAuthenticate = true;

            // Create a WebRequest that authenticates the current user
            // with Windows integrated authentication.
            WebRequest requestB = WebRequest.Create("http://www.somesite.com");

            requestB.Credentials     = CredentialCache.DefaultCredentials;
            requestB.PreAuthenticate = true;

            // Create a WebRequest that authenticates the user with a client
            // certificate loaded from a file.
            HttpWebRequest requestC =
                (HttpWebRequest)WebRequest.Create("http://www.somesite.com");
            X509Certificate cert1 =
                X509Certificate.CreateFromCertFile(@"..\..\TestCertificate.cer");

            requestC.ClientCertificates.Add(cert1);

            // Create a WebRequest that authenticates the user with a client
            // certificate loaded from a certificate store. Try to find a
            // certificate with a specific subject, but if it is not found
            // present the user with a dialog so they can select the certificate
            // to use from their personal store.
            HttpWebRequest requestD =
                (HttpWebRequest)WebRequest.Create("http://www.somesite.com");
            X509Store store = new X509Store();
            X509Certificate2Collection certs =
                store.Certificates.Find(X509FindType.FindBySubjectName,
                                        "Allen Jones", false);

            if (certs.Count == 1)
            {
                requestD.ClientCertificates.Add(certs[0]);
            }
            else
            {
                certs = X509Certificate2UI.SelectFromCollection(
                    store.Certificates,
                    "Select Certificate",
                    "Select the certificate to use for authentication.",
                    X509SelectionFlag.SingleSelection);

                if (certs.Count != 0)
                {
                    requestD.ClientCertificates.Add(certs[0]);
                }
            }

            // Now issue the request and process the responses...
        }
Esempio n. 3
0
        static async Task <int> SslConnectionTestAsync()
        {
            try
            {
                ConnectionFactory factory = new ConnectionFactory();

                String certFile = "c:\\Users\\JAkub\\Downloads\\ABCFR_ABCFRALMMACC1.crt";
                factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
                factory.SSL.LocalCertificateSelectionCallback   = (a, b, c, d, e) => X509Certificate.CreateFromCertFile(certFile);
                factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certFile));

                factory.AMQP.MaxFrameSize = 64 * 1024;
                factory.AMQP.ContainerId  = "fixml-client";

                factory.SASL.Profile = SaslProfile.External;

                Trace.TraceLevel    = TraceLevel.Frame;
                Trace.TraceListener = (f, a) => Console.WriteLine(String.Format(f, a));

                Connection.DisableServerCertValidation = false;

                Address    brokerAddress = new Address("amqps://ecag-fixml-simu1.deutsche-boerse.com:10170");
                Connection connection    = await factory.CreateAsync(brokerAddress);

                Session session = new Session(connection);

                ReceiverLink receiver = new ReceiverLink(session, "broadcast-receiver", "broadcast.ABCFR_ABCFRALMMACC1.TradeConfirmation");

                while (true)
                {
                    Message msg = receiver.Receive(60000);

                    if (msg == null)
                    {
                        break;
                    }

                    Amqp.Framing.Data payload     = (Amqp.Framing.Data)msg.BodySection;
                    String            payloadText = Encoding.UTF8.GetString(payload.Binary);

                    Console.WriteLine("Received message: {0}", payloadText);
                    receiver.Accept(msg);
                }

                Console.WriteLine("No message received for 60 seconds");

                await connection.CloseAsync();

                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                return(1);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 发送SSL加密请求
        /// </summary>
        /// <param name="post_data"></param>
        /// <param name="url"></param>
        /// <param name="cert_path"></param>
        /// <param name="cert_password"></param>
        /// <param name="errInfo"></param>
        /// <returns></returns>
        public static string PostDataBySSL(string post_data, string url, string cert_path, string cert_password, out string errInfo)
        {
            errInfo = string.Empty;
            try
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[]        data     = encoding.GetBytes(post_data);
                if (cert_path != string.Empty)
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
                }

                WebRequest     webRequest  = WebRequest.Create(url);
                HttpWebRequest httpRequest = webRequest as HttpWebRequest;

                if (cert_path.ToLower().EndsWith(".cer"))
                {
                    httpRequest.ClientCertificates.Add(X509Certificate.CreateFromCertFile(cert_path));
                }

                else
                {
                    //SpringFactory.BusinessFactory.GetBusinessAnonymousUser().AddLogs(cert_path);
                    httpRequest.ClientCertificates.Add(new X509Certificate2(cert_path, cert_password, X509KeyStorageFlags.MachineKeySet));
                }
                httpRequest.KeepAlive   = true;
                httpRequest.UserAgent   = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";
                httpRequest.ContentType = "application/x-www-form-urlencoded";
                httpRequest.Method      = "POST";

                httpRequest.ContentLength = data.Length;
                Stream requestStream = httpRequest.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
                Stream responseStream = null;
                responseStream = httpRequest.GetResponse().GetResponseStream();
                string stringResponse = string.Empty;
                if (responseStream != null)
                {
                    using (StreamReader responseReader =
                               new StreamReader(responseStream, Encoding.GetEncoding("GBK")))
                    {
                        stringResponse = responseReader.ReadToEnd();
                    }
                    responseStream.Close();
                }
                return(stringResponse);
            }
            catch (Exception e)
            {
                errInfo = e.Message;

                SpringFactory.BusinessFactory.GetBusinessAnonymousUser().AddLogs(e.Message);
                return(string.Empty);
            }
        }
 public bool NegTest8(string fileName)
 {
     return(NegTest(8, "X509Certificate.CreateFromFile()", fileName,
                    delegate(string fName)
     {
         X509Certificate cer;
         cer = X509Certificate.CreateFromCertFile(fName);
         return false;
     }));
 }
        public DeviceSimulator()
        {
            CaCert     = X509Certificate.CreateFromCertFile(path + "\\certificates\\root-CA.crt");
            ClientCert = new X509Certificate2(path + "\\certificates\\2.pfx", "");

            IotClient = new MqttClient(iotendpoint, brokerPort, true, CaCert, ClientCert, MqttSslProtocols.TLSv1_2);

            IotClient.Subscribe(topics, qosLevels);
            IotClient.MqttMsgPublishReceived += IotClient_MqttMsgPublishReceived;
        }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TTLSSocket"/> class.
 /// </summary>
 /// <param name="host">The host, where the socket should connect to.</param>
 /// <param name="port">The port.</param>
 /// <param name="certificatePath">The certificate path.</param>
 /// <param name="certValidator">User defined cert validator.</param>
 /// <param name="localCertificateSelectionCallback">The callback to select which certificate to use.</param>
 /// <param name="sslProtocols">The SslProtocols value that represents the protocol used for authentication.</param>
 public TTLSSocket(
     String host,
     Int32 port,
     String certificatePath,
     RemoteCertificateValidationCallback certValidator = null,
     LocalCertificateSelectionCallback localCertificateSelectionCallback = null,
     SslProtocols sslProtocols = SslProtocols.Tls)
     : this(host, port, 0, X509Certificate.CreateFromCertFile(certificatePath), certValidator, localCertificateSelectionCallback, sslProtocols)
 {
 }
Esempio n. 8
0
    // Create a signature and add it to the specified document.
    private static void SignDocument(ref XmlDocument xmlDoc)
    {
        // Generate a signing key.
        RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(xmlDoc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();

        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        reference.AddTransform(new XmlDsigC14NTransform());

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        try
        {
            // Create a new KeyInfo object.
            KeyInfo keyInfo = new KeyInfo();

            // Load the X509 certificate.
            X509Certificate MSCert =
                X509Certificate.CreateFromCertFile(Certificate);

            // Load the certificate into a KeyInfoX509Data object
            // and add it to the KeyInfo object.
            keyInfo.AddClause(new KeyInfoX509Data(MSCert));

            // Add the KeyInfo object to the SignedXml object.
            signedXml.KeyInfo = keyInfo;
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Unable to locate the following file: " +
                              Certificate);
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("Unexpected exception caught whild creating " +
                              "the certificate:" + ex.ToString());
        }

        // Compute the signature.
        signedXml.ComputeSignature();

        // Add the signature branch to the original tree so it is enveloped.
        xmlDoc.DocumentElement.AppendChild(signedXml.GetXml());
    }
Esempio n. 9
0
        public RtmpServer(RtmpEndpoint endpoint)
        {
            _connections     = new Hashtable();
            _socketListeners = new ArrayList();
            _endpoint        = endpoint;
            _rtmpHandler     = new RtmpHandler(endpoint);

            try {
                if (endpoint.ChannelDefinition.Properties.KeystoreFile != null)
                {
                    FileSystemResource fsr = new FileSystemResource(endpoint.ChannelDefinition.Properties.KeystoreFile);
                    if (fsr.Exists)
                    {
                        if (endpoint.ChannelDefinition.Properties.KeystorePassword != null)
                        {
                            _serverCertificate = new X509Certificate2(fsr.File.FullName, endpoint.ChannelDefinition.Properties.KeystorePassword);
                        }
                        else
                        {
                            _serverCertificate = X509Certificate.CreateFromCertFile(fsr.File.FullName);
                        }
                        log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString()));
                    }
                    else
                    {
                        log.Error("Certificate file not found");
                    }
                }
                else
                {
                    if (endpoint.ChannelDefinition.Properties.ServerCertificate != null)
                    {
                        StoreName     storeName     = (StoreName)Enum.Parse(typeof(StoreName), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreName, false);
                        StoreLocation storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreLocation, false);
                        X509FindType  x509FindType  = (X509FindType)Enum.Parse(typeof(X509FindType), endpoint.ChannelDefinition.Properties.ServerCertificate.X509FindType, false);
                        X509Store     store         = new X509Store(storeName, storeLocation);
                        store.Open(OpenFlags.ReadOnly);
                        X509Certificate2Collection certificateCollection = store.Certificates.Find(x509FindType, endpoint.ChannelDefinition.Properties.ServerCertificate.FindValue, false);
                        X509Certificate2Enumerator enumerator            = certificateCollection.GetEnumerator();
                        if (enumerator.MoveNext())
                        {
                            _serverCertificate = enumerator.Current;
                            log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString()));
                        }
                        else
                        {
                            log.Error("Certificate not found");
                        }
                    }
                }
            } catch (Exception ex) {
                log.Error("Error loading certificate.", ex);
            }
        }
Esempio n. 10
0
        public SslTcpServer(int incommingPort, string outcommingIP, int outcommingPort, string certificatePath)
        {
            this.outcommingIP   = outcommingIP;
            this.outcommingPort = outcommingPort;
            this.incommingPort  = incommingPort;

            if (!string.IsNullOrEmpty(certificatePath))
            {
                serverCertificate = X509Certificate.CreateFromCertFile(certificatePath);
            }
        }
Esempio n. 11
0
        private static X509Certificate2 GetCertificateFromPath(string certPath)
        {
            if (!new FileInfo(certPath).Exists)
            {
                throw new Exception($"Certificate {certPath} not found");
            }
            var cert1 = X509Certificate.CreateFromCertFile(certPath);
            var cert2 = new X509Certificate2(cert1);

            return(cert2);
        }
Esempio n. 12
0
        public void LoginToServer()
        {
            // Start server
            var serverControl = new MainServerControl();


            // ADD REMOTE ACCESS
            ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => true;
            var clientConnection = new TcpClient();

            clientConnection.Connect("192.168.1.217", 3000);

            var clientStream      = new SslStream(clientConnection.GetStream(), false, ValidateServerCertificate, null);
            var serverCertificate = X509Certificate.CreateFromCertFile(Thread.GetDomain().BaseDirectory + "rolandio.cer");
            var certificates      = new X509CertificateCollection(new[] { serverCertificate });

            clientStream.AuthenticateAsClient("192.168.1.217", certificates, SslProtocols.Default, false);
            var bytesToSend = Encoding.ASCII.GetBytes("LOGIN\r\n");

            clientStream.Write(bytesToSend, 0, bytesToSend.Length);


            // Get Response
            var loginResponse = GetMessageFromServer(clientStream);

            if (loginResponse.Trim() == "200 OK")
            {
                SendMessageToServer(clientStream, "CLIENT_1027\r\n");

                // Get Response
                var userMessage = GetMessageFromServer(clientStream);
                if (userMessage.Equals("PASSWORD"))
                {
                    SendMessageToServer(clientStream, "12345678\r\n");

                    // Get Response
                    var loginIsAcceptedResponse = GetMessageFromServer(clientStream);
                    if (loginIsAcceptedResponse.Equals("LOGIN 200 OK"))
                    {
                        _loggedInCredentials = clientStream;


                        // Simmple test
                        SendMessageToServer(clientStream, "LOOK UP SINGLE HASH\r\n");
                        var readyForHash = GetMessageFromServer(clientStream);
                        if (readyForHash.Equals("200 OK"))
                        {
                            SendMessageToServer(clientStream, "00f538c3d410822e241486ca061a57ee$\r\n");
                            var report = GetMessageFromServer(clientStream);
                        }
                    }
                }
            }
        }
Esempio n. 13
0
    public static string ReadCert()
    {
        // The path to the certificate.
        string Certificate = HttpContext.Current.Server.MapPath("~/Certificate/HealthReunionHealthVaultIntegration.cer");

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

        // return certificate raw data string
        return(cert.GetRawCertDataString());
    }
Esempio n. 14
0
    public static void Main()
    {
        // The path to the certificate.
        string Certificate = "Certificate.cer";

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

        // Get the value.
        byte[] results = cert.GetCertHash();
    }
Esempio n. 15
0
        private X509Certificate GetCertificate()
        {
            const string sertFileName = "cer/der.cer";

            if (File.Exists(sertFileName))
            {
                return(X509Certificate.CreateFromCertFile(sertFileName));
            }

            return(new X509Certificate());
        }
Esempio n. 16
0
        public static void Init()
        {
            string          IotEndPoint = "*********-ats.iot.us-east-2.amazonaws.com";                        //AWS Endpoint
            X509Certificate CaCert      = X509Certificate.CreateFromCertFile(@"C:\Location\root-CA.crt");     //Directory of AWS Root Certificate
            X509Certificate ClientCert  = new X509Certificate2(@"C:\Location\Cert.pfx", "PasswordOfPFXFile"); //Directory of Device Certificate in pfx format and password for the pfx file

            string ClientId = Guid.NewGuid().ToString();

            IotClient = new MqttClient(IotEndPoint, 8883, true, CaCert, ClientCert, MqttSslProtocols.TLSv1_2);
            IotClient.Connect(ClientId);
            //while (!IotClient.IsConnected) { }
        }
        public override void ExecuteCommand()
        {
            X509Certificate cert    = X509Certificate.CreateFromCertFile(CertificateName);
            HttpWebRequest  request = (HttpWebRequest)WebRequest.Create(string.Format("https://management.core.windows.net/{0}/services/WATM/profiles/{1}/definitions", SubscriptionId, ProfileName));

            request.ClientCertificates.Add(cert);
            request.Headers.Add("x-ms-version: 2014-02-01");
            request.PreAuthenticate = true;
            request.Method          = "GET";
            var response = request.GetResponse();

            //Schema of the response would be as specified in http://msdn.microsoft.com/en-us/library/azure/hh758251.aspx
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var responseContent = reader.ReadToEnd();
                Console.WriteLine(responseContent);

                var responseDoc = new XmlDocument();
                responseDoc.LoadXml(responseContent);
                var endpointNodes = responseDoc.GetElementsByTagName("Endpoint", "http://schemas.microsoft.com/windowsazure");
                //Endpoint Structure
                //<Endpoint >
                //    <DomainName>    Name                </DomainName>
                //    <Status>        Enabled             </Status>
                //    <Type>          CloudService        </Type>
                //    <Location>      North Central US    </Location>
                //    <MonitorStatus> Online              </MonitorStatus>
                //    <Weight>        1                   </Weight>
                //</Endpoint>

                var endpointValues = new List <Tuple <string, string> >();
                foreach (XmlNode endpointNode in endpointNodes)
                {
                    string endpointName   = endpointNode["DomainName"].InnerText;
                    string endpointStatus = endpointNode["MonitorStatus"].InnerText;
                    Console.WriteLine(string.Format("Endpoint name {0}, status {1}", endpointName, endpointStatus));
                    endpointValues.Add(Tuple.Create(endpointName, endpointStatus));
                    if (!endpointStatus.Equals("Online", StringComparison.OrdinalIgnoreCase))
                    {
                        new SendAlertMailTask
                        {
                            AlertSubject = string.Format("Error: Traffic manager endpoint alert activated for {0}", endpointName),
                            Details      = string.Format("The status of the endpoint {0} monitoring by traffic manager {1} is {2}", endpointName, ProfileName, endpointStatus),
                            AlertName    = "Error: Alert for TrafficManagerEndpoint",
                            Component    = "TrafficManager",
                            Level        = "Error"
                        }.ExecuteCommand();
                    }
                }
                JArray reportObject = ReportHelpers.GetJson(endpointValues);
                ReportHelpers.CreateBlob(StorageAccount, "TrafficManagerStatus.json", ContainerName, "application/json", ReportHelpers.ToStream(reportObject));
            }
        }
Esempio n. 18
0
        public void CheckStoreAndLoadRA()
        {
            SimiasAccessLogger accessLog = new SimiasAccessLogger("Service", "Loading RA's");
            Store store = Store.GetStore();

            //Load the RSA for the domain - need to see how this can be migrated --FIXME
            if (store.DefaultDomain != null)
            {
                //Store the DEFAULT certificate(RSA information) for users using the "Server Default" option in client
                // need to find a better way of representing DEFAULT
                Simias.Security.RSAStore.CheckAndStoreRSA(store.DefaultRSARA.ToXmlString(true), "DEFAULT", true);
            }
            X509Certificate raCert = null;

            try
            {
                Simias.Configuration config = Store.Config;
                string raPath = config.Get("Server", "RAPath");

                if (raPath != null && raPath != String.Empty && raPath != "")
                {
                    string[] racertFiles = Directory.GetFiles(raPath, "*.?er");
                    Simias.Security.CertificateStore.CleanCertsFromStore();
                    foreach (string file in racertFiles)
                    {
                        try
                        {
                            raCert = X509Certificate.CreateFromCertFile(file);
                        }
                        catch (CryptographicException ce)
                        {
                            log.Debug("Exception {0}, File: {1}", ce.ToString(), file);
                            continue;
                        }
                        //Simias.Security.CertificateStore.StoreRACertificate (raCert.GetRawCertData(), raCert.GetName().ToLower(), true);
                        Simias.Security.CertificateStore.StoreRACertificate(raCert.GetRawCertData(), Path.GetFileNameWithoutExtension(file).ToLower(), true);
                        accessLog.LogAccess("CheckStoreAndLoadRA", "Loading RecoveryAgent", "-", raCert.GetName());
                    }
                }
            }
            catch (Exception e)
            {
                log.Error(e.ToString());
                accessLog.LogAccess("CheckStoreAndLoadRA", "Failed Loading RecoveryAgent", "-", "-");
            }

            Simias.Security.CertificateStore.LoadRACertsFromStore(); //this loads all Certs including RA - but client will not have RA
            if (store.DefaultDomain != null)                         //load the RSA data from store - only on server
            {
                Simias.Security.RSAStore.LoadRSAFromStore();
            }
        }
Esempio n. 19
0
 internal static X509Certificate CreateCertificateFromFile(string pathToCertificate)
 {
     try
     {
         var certificate = X509Certificate.CreateFromCertFile(pathToCertificate);
         return(certificate);
     }
     catch (CryptographicException exception)
     {
         Console.WriteLine($"There was an error proccessing the certificate path - {exception.ToString()}");
         throw;
     }
 }
Esempio n. 20
0
        private static void SetCertificate()
        {
            var cloudCertificate =
                new X509Certificate2(
                    X509Certificate.CreateFromCertFile(ResourcesDirectory + @"ssl/cloud.neowutran.ovh.der"));

            ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) =>
                certificate.Equals(cloudCertificate);

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
        }
Esempio n. 21
0
        static void Main(string[] args)
        {
            serverCertificate = X509Certificate.CreateFromCertFile("output2.cer");
            TcpListener listener = new TcpListener(IPAddress.Any, 8088);

            listener.Start();
            Console.WriteLine("Server run on: https://localhost:8088 ");
            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                ThreadPool.QueueUserWorkItem(ProcessClient, client);
            }
        }
Esempio n. 22
0
        private void InitializeClient(string iotEndpoint, string certificatePath, string rootCertificate,
                                      string certificate, string certificateKey)
        {
            var caCert     = X509Certificate.CreateFromCertFile(Path.Join(certificatePath, rootCertificate));
            var clientCert = _certificateLoader.LoadX509Certificate(certificatePath, certificate, certificateKey);

            MqttClient = new MqttClient(iotEndpoint, 8883, true, caCert, clientCert, MqttSslProtocols.TLSv1_2);

            MqttClient.MqttMsgPublished       += ClientOnMqttMsgPublished;
            MqttClient.MqttMsgSubscribed      += ClientOnMqttMsgSubscribed;
            MqttClient.MqttMsgUnsubscribed    += ClientOnMqttMsgUnsubscribed;
            MqttClient.MqttMsgPublishReceived += ClientOnMqttMsgPublishReceived;
        }
Esempio n. 23
0
        public static (Option <IList <X509Certificate2> >, Option <string>) GetCertsAtPath(string path)
        {
            Preconditions.CheckNonWhiteSpace(path, nameof(path));

            var cert = new X509Certificate2(X509Certificate.CreateFromCertFile(path));

            (IList <X509Certificate2> chainCerts, Option <string> errors) = BuildCertificateList(cert);
            if (errors.HasValue)
            {
                return(Option.None <IList <X509Certificate2> >(), errors);
            }
            return(Option.Some(chainCerts), Option.None <string>());
        }
        static async Task <int> SslConnectionTestAsync()
        {
            try{
                ConnectionFactory factory = new ConnectionFactory();

                String certFile = "C:\\location\\certificate.cer";
                factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
                factory.SSL.LocalCertificateSelectionCallback   = (a, b, c, d, e) => X509Certificate.CreateFromCertFile(certFile);
                factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certFile));

                factory.SASL.Profile = SaslProfile.External;
                Connection.DisableServerCertValidation = false;

                Address    address    = new Address("amqps://*****:*****@host:5671");
                Connection connection = await factory.CreateAsync(address);

                Session    session = new Session(connection);
                SenderLink sender  = new SenderLink(session, "sender-link", "amqp");
                Message    message = null;

                DateTime d1 = DateTime.Now;
                Console.WriteLine(d1);
                Console.WriteLine("Send Start time : {0}!", d1);

                for (int i = 0; i < 5; i++)
                {
                    string msg = "num --" + i + "-->this is a testing message for sender, to test sending proformance";
                    message = new Message(msg);
                    sender.SendAsync(message);
                    Console.WriteLine("Sent messaging {0}!", msg);
                }

                DateTime d2 = DateTime.Now;
                Console.WriteLine("Send End time : {0}!", d2);
                Console.WriteLine("Press enter key to exit...");
                Console.ReadLine();

                await sender.CloseAsync();

                await session.CloseAsync();

                await connection.CloseAsync();

                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                return(1);
            }
        }
Esempio n. 25
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="pemFile"></param>
 /// <returns></returns>
 private bool LoadX509Certificate()
 {
     try
     {
         var x509Cert = X509Certificate.CreateFromCertFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, config.CertificateFileName));
         ExtendedHttpClient.x509Cert = x509Cert;
         return(true);
     }
     catch (Exception ex)
     {
         EventLog.WriteEntry(Global.DISPLAY_NAME, "Error loading certificate: " + ex.Message, EventLogEntryType.Error);
         return(false);
     }
 }
Esempio n. 26
0
        static void Main(string[] args)
        {
            // Test Invoke-RestMethod -Uri http://127.0.0.1:8080/ -Method Post -InFile .\test.cs -OutFile .\foo.exe

            string compilerPath = "C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\csc.exe";

            if (args.Count() > 0)
            {
                compilerPath = args[0];
            }
            using (var httpServer = new HttpServer(new HttpRequestProvider()))
            {
                if (System.IO.File.Exists(@"cert.cer"))
                {
                    int port = 443;
                    if (args.Count() > 1)
                    {
                        port = int.Parse(args[1]);
                    }
                    var serverCertificate = X509Certificate.CreateFromCertFile(@"cert.cer");
                    httpServer.Use(new ListenerSslDecorator(new TcpListenerAdapter(new TcpListener(IPAddress.Any, port)), serverCertificate));
                }
                else
                {
                    int port = 80;
                    if (args.Count() > 1)
                    {
                        port = int.Parse(args[1]);
                    }
                    httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, port)));
                }
                // Request handling :
                httpServer.Use((context, next) => {
                    Console.WriteLine("Got Request!");
                    return(next());
                });

                // Handler classes :
                httpServer.Use(new TimingHandler());
                httpServer.Use(new HttpRouter().With(string.Empty, new IndexHandler(compilerPath))
                               .With("about", new IndexHandler(compilerPath)));

                httpServer.Use(new FileHandler());
                httpServer.Use(new ErrorHandler());

                httpServer.Start();

                Console.ReadLine();
            }
        }
Esempio n. 27
0
    public static void Main()
    {
        // The path to the certificate.
        string Certificate = "Certificate.cer";

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

        // Get the value.
        string results = cert.GetKeyAlgorithmParametersString();

        // Display the value to the console.
        Console.WriteLine(results);
    }
        // The certificate parameter specifies the name of the file
        // containing the machine certificate. File cert.pem in Certificate catalog
        public void RunServer(string certificate)
        {
            serverCertificate = X509Certificate.CreateFromCertFile(certificate);

            listener = new TcpListener(IPAddress.Any, 8080);
            listener.Start();
            while (true)
            {
                Console.WriteLine("Waiting for a client to connect...");

                TcpClient client = listener.AcceptTcpClient();
                ProcessClient(client);
            }
        }
Esempio n. 29
0
 public static string LoadCertificate(string fileName)
 {
     try
     {
         _sslCertificate = X509Certificate.CreateFromCertFile(fileName);
         Logger.LogMessage("Loaded SSL Certificate: " + _sslCertificate.ToString(false));
         return("OK");
     }
     catch (Exception ex)
     {
         Logger.LogException(ex);
         return(ex.Message);
     }
 }
        public async Task <CertInfo?> GetCertInfo(string identifier)
        {
            var path = Path.Combine(this.root, identifier + ".pfx");

            if (File.Exists(path) == false)
            {
                return(null);
            }

            using var oldCert = X509Certificate.CreateFromCertFile(path);
            using var cert    = new X509Certificate2(oldCert);

            return(new CertInfo(identifier, cert));
        }