Example #1
0
        public void CreateCrs(string name, string keyname, CertificateDetails certificateDetails)
        {
            var command = CreateCrsCommand(name, keyname, certificateDetails);

            try {
                _sshClient.RunCommand(command);
            } catch (Exception e) {
                throw new Exception("Error while generating crs. The following error occured: " + e.Message);
            }
        }
 public object PerformWithParam(object value, object parameter)
 {
     if (value is NDjangoWrapper.ErrorTemplate)
     {
         throw new Exception("Value does not exist when calling decrypt");
     }
     else
     {
         var cert      = new CertificateDetails(StoreLocation.LocalMachine, StoreName.My, (string)parameter);
         var data      = Convert.FromBase64String((string)value);
         var decrypted = Decrypt(cert, data);
         return(Encoding.UTF8.GetString(decrypted));
     }
 }
        /// <summary>
        /// Calls [usp_Get_CertificateByCompany]
        /// </summary>
        /// <returns></returns>
        public override List <CertificateDetails> GetCertificateByCompany(System.Int32?companyNo)
        {
            SqlConnection cn  = null;
            SqlCommand    cmd = null;

            try
            {
                cn              = new SqlConnection(this.ConnectionString);
                cmd             = new SqlCommand("usp_get_CertificateByCompany", cn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@CompanyNo", SqlDbType.Int).Value = companyNo;
                cmd.CommandTimeout = 30;
                cn.Open();
                DbDataReader reader           = ExecuteReader(cmd);
                List <CertificateDetails> lst = new List <CertificateDetails>();
                while (reader.Read())
                {
                    CertificateDetails obj = new CertificateDetails();
                    obj.CompanyCertificateId  = GetReaderValue_Int32(reader, "CompanyCertificateId", 0);
                    obj.CertificateId         = GetReaderValue_Int32(reader, "CertificateNo", 0);
                    obj.CertificateCategoryNo = GetReaderValue_Int32(reader, "CertificateCategoryNo", 0);
                    obj.CertificateName       = GetReaderValue_String(reader, "CertificateName", "");
                    obj.Description           = GetReaderValue_String(reader, "Description", "");
                    obj.Inactive   = GetReaderValue_Boolean(reader, "Inactive", false);
                    obj.StartDate  = GetReaderValue_NullableDateTime(reader, "StartDate", null);
                    obj.ExpiryDate = GetReaderValue_NullableDateTime(reader, "ExpiryDate", null);
                    obj.UpdatedBy  = GetReaderValue_NullableInt32(reader, "UpdatedBy", 0);
                    obj.DLUP       = GetReaderValue_DateTime(reader, "DLUP", DateTime.MinValue);
                    obj.CertificateCategoryName = GetReaderValue_String(reader, "CertificateCategoryName", "");
                    obj.CertificateNumber       = GetReaderValue_String(reader, "CertificateNumber", "");
                    lst.Add(obj);
                    obj = null;
                }
                return(lst);
            }
            catch (SqlException sqlex)
            {
                //LogException(sqlex);
                throw new Exception("Failed to get company certificate", sqlex);
            }
            finally
            {
                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
        }
        public byte[] Decrypt(CertificateDetails details, byte[] data)
        {
            var exceptions = new List <Exception>();

            foreach (var certificate in FindCertificates(details))
            {
                try
                {
                    var rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
                    return(rsa.Decrypt(data, true));
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }

            throw new CryptographicException($"Could not decrypt data using any found certificate with subject name '{details.CertificateSubjectName}' in the store {details.Location}/{details.Name}:{Environment.NewLine} - {String.Join($"{Environment.NewLine} - ", exceptions.Select(e => e.Message))}");
        }
Example #5
0
        private static byte[] Decrypt(CertificateDetails details, byte[] data)
        {
            var exceptions = new List <Exception>();

            foreach (var certificate in FindCertificates(details))
            {
                try
                {
                    using (var rsa = certificate.GetRSAPrivateKey())
                    {
                        return(rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA1));
                    }
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }

            throw new CryptographicException($"Could not decrypt data using any found certificate with subject name '{details.CertificateSubjectName}' in the store {details.Location}/{details.Name}:{Environment.NewLine} - {string.Join($"{Environment.NewLine} - ", exceptions.Select(e => e.Message))}");
        }
        /// <summary>
        /// Get
        /// Calls [usp_select_Certificate]
        /// </summary>
        public override CertificateDetails Get(System.Int32?certificateId)
        {
            SqlConnection cn  = null;
            SqlCommand    cmd = null;

            try {
                cn                 = new SqlConnection(this.ConnectionString);
                cmd                = new SqlCommand("usp_select_Certificate", cn);
                cmd.CommandType    = CommandType.StoredProcedure;
                cmd.CommandTimeout = 30;
                cmd.Parameters.Add("@CertificateId", SqlDbType.Int).Value = certificateId;
                cn.Open();
                DbDataReader reader = ExecuteReader(cmd, CommandBehavior.SingleRow);
                if (reader.Read())
                {
                    CertificateDetails obj = new CertificateDetails();
                    obj.CertificateId         = GetReaderValue_Int32(reader, "CertificateId", 0);
                    obj.CertificateName       = GetReaderValue_String(reader, "CertificateName", "");
                    obj.Description           = GetReaderValue_String(reader, "Description", "");
                    obj.CertificateCategoryNo = GetReaderValue_Int32(reader, "CertificateCategoryNo", 0);
                    obj.Inactive  = GetReaderValue_Boolean(reader, "Inactive", false);
                    obj.UpdatedBy = GetReaderValue_NullableInt32(reader, "UpdatedBy", null);
                    obj.DLUP      = GetReaderValue_DateTime(reader, "DLUP", DateTime.MinValue);
                    return(obj);
                }
                else
                {
                    return(null);
                }
            } catch (SqlException sqlex) {
                //LogException(sqlex);
                throw new Exception("Failed to get Certificate", sqlex);
            } finally {
                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
        }
 internal AppServiceCertificateOrderData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, IDictionary <string, string> tags, AzureLocation location, string kind, IDictionary <string, AppServiceCertificate> certificates, string distinguishedName, string domainVerificationToken, int?validityInYears, int?keySize, CertificateProductType?productType, bool?autoRenew, ProvisioningState?provisioningState, CertificateOrderStatus?status, CertificateDetails signedCertificate, string csr, CertificateDetails intermediate, CertificateDetails root, string serialNumber, DateTimeOffset?lastCertificateIssuanceTime, DateTimeOffset?expirationTime, bool?isPrivateKeyExternal, IReadOnlyList <AppServiceCertificateNotRenewableReason> appServiceCertificateNotRenewableReasons, DateTimeOffset?nextAutoRenewalTimeStamp, CertificateOrderContact contact) : base(id, name, type, systemData, tags, location, kind)
 {
     Certificates            = certificates;
     DistinguishedName       = distinguishedName;
     DomainVerificationToken = domainVerificationToken;
     ValidityInYears         = validityInYears;
     KeySize           = keySize;
     ProductType       = productType;
     AutoRenew         = autoRenew;
     ProvisioningState = provisioningState;
     Status            = status;
     SignedCertificate = signedCertificate;
     Csr          = csr;
     Intermediate = intermediate;
     Root         = root;
     SerialNumber = serialNumber;
     LastCertificateIssuanceTime = lastCertificateIssuanceTime;
     ExpirationTime       = expirationTime;
     IsPrivateKeyExternal = isPrivateKeyExternal;
     AppServiceCertificateNotRenewableReasons = appServiceCertificateNotRenewableReasons;
     NextAutoRenewalTimeStamp = nextAutoRenewalTimeStamp;
     Contact = contact;
 }
 public PrintingJsonCreator(
     IOptions <CertificateDetails> options)
 {
     _certificateDetails = options?.Value;
 }
        internal static AppServiceCertificateOrderData DeserializeAppServiceCertificateOrderData(JsonElement element)
        {
            Optional <string>            kind = default;
            IDictionary <string, string> tags = default;
            AzureLocation      location       = default;
            ResourceIdentifier id             = default;
            string             name           = default;
            ResourceType       type           = default;
            SystemData         systemData     = default;
            Optional <IDictionary <string, AppServiceCertificate> > certificates = default;
            Optional <string> distinguishedName       = default;
            Optional <string> domainVerificationToken = default;
            Optional <int>    validityInYears         = default;
            Optional <int>    keySize = default;
            Optional <CertificateProductType> productType = default;
            Optional <bool> autoRenew = default;
            Optional <ProvisioningState>      provisioningState = default;
            Optional <CertificateOrderStatus> status            = default;
            Optional <CertificateDetails>     signedCertificate = default;
            Optional <string>             csr          = default;
            Optional <CertificateDetails> intermediate = default;
            Optional <CertificateDetails> root         = default;
            Optional <string>             serialNumber = default;
            Optional <DateTimeOffset>     lastCertificateIssuanceTime = default;
            Optional <DateTimeOffset>     expirationTime = default;
            Optional <bool> isPrivateKeyExternal         = default;
            Optional <IReadOnlyList <AppServiceCertificateNotRenewableReason> > appServiceCertificateNotRenewableReasons = default;
            Optional <DateTimeOffset>          nextAutoRenewalTimeStamp = default;
            Optional <CertificateOrderContact> contact = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("kind"))
                {
                    kind = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("certificates"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            Dictionary <string, AppServiceCertificate> dictionary = new Dictionary <string, AppServiceCertificate>();
                            foreach (var property1 in property0.Value.EnumerateObject())
                            {
                                dictionary.Add(property1.Name, AppServiceCertificate.DeserializeAppServiceCertificate(property1.Value));
                            }
                            certificates = dictionary;
                            continue;
                        }
                        if (property0.NameEquals("distinguishedName"))
                        {
                            distinguishedName = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("domainVerificationToken"))
                        {
                            domainVerificationToken = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("validityInYears"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            validityInYears = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("keySize"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            keySize = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("productType"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            productType = property0.Value.GetString().ToCertificateProductType();
                            continue;
                        }
                        if (property0.NameEquals("autoRenew"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            autoRenew = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = property0.Value.GetString().ToProvisioningState();
                            continue;
                        }
                        if (property0.NameEquals("status"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            status = property0.Value.GetString().ToCertificateOrderStatus();
                            continue;
                        }
                        if (property0.NameEquals("signedCertificate"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            signedCertificate = CertificateDetails.DeserializeCertificateDetails(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("csr"))
                        {
                            csr = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("intermediate"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            intermediate = CertificateDetails.DeserializeCertificateDetails(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("root"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            root = CertificateDetails.DeserializeCertificateDetails(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("serialNumber"))
                        {
                            serialNumber = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("lastCertificateIssuanceTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            lastCertificateIssuanceTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("expirationTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            expirationTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("isPrivateKeyExternal"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            isPrivateKeyExternal = property0.Value.GetBoolean();
                            continue;
                        }
                        if (property0.NameEquals("appServiceCertificateNotRenewableReasons"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <AppServiceCertificateNotRenewableReason> array = new List <AppServiceCertificateNotRenewableReason>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(new AppServiceCertificateNotRenewableReason(item.GetString()));
                            }
                            appServiceCertificateNotRenewableReasons = array;
                            continue;
                        }
                        if (property0.NameEquals("nextAutoRenewalTimeStamp"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            nextAutoRenewalTimeStamp = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("contact"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            contact = CertificateOrderContact.DeserializeCertificateOrderContact(property0.Value);
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new AppServiceCertificateOrderData(id, name, type, systemData, tags, location, kind.Value, Optional.ToDictionary(certificates), distinguishedName.Value, domainVerificationToken.Value, Optional.ToNullable(validityInYears), Optional.ToNullable(keySize), Optional.ToNullable(productType), Optional.ToNullable(autoRenew), Optional.ToNullable(provisioningState), Optional.ToNullable(status), signedCertificate.Value, csr.Value, intermediate.Value, root.Value, serialNumber.Value, Optional.ToNullable(lastCertificateIssuanceTime), Optional.ToNullable(expirationTime), Optional.ToNullable(isPrivateKeyExternal), Optional.ToList(appServiceCertificateNotRenewableReasons), Optional.ToNullable(nextAutoRenewalTimeStamp), contact.Value));
        }
Example #10
0
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            Console.WriteLine("Secure Socket Layer (SSL) Example ...\n");

            //Ensure we have a certificate to use
            //Maximum security is achieved by using a trusted certificate
            //To keep things simple here we just create a self signed certificate for testing
            string certName = "testCertificate.pfx";

            if (!File.Exists(certName))
            {
                Console.WriteLine("Creating self-signed test certificate - " + certName);
                CertificateDetails details = new CertificateDetails("CN=networkcomms.net", DateTime.Now, DateTime.Now.AddYears(1));

                //We could increase/decrease the default key length if we want
                details.KeyLength = 1024;

                //Save the certificate to disk
                SSLTools.CreateSelfSignedCertificatePFX(details, certName);
                certificate = new X509Certificate2(certName);
                Console.WriteLine("\t... certificate successfully created.");
            }
            else
            {
                //Load an existing certificate
                Console.WriteLine("Loading existing certificate - " + certName);
                certificate = new X509Certificate2(certName);
                Console.WriteLine("\t... certificate successfully loaded.");
            }

            //Add a global incoming packet handler for packets of type "Message"
            //This handler will convert the incoming raw bytes into a string (this is what
            //the <string> bit means) and then write that string to the local console window.
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", (packetHeader, connection, incomingString) =>
            {
                Console.WriteLine("\n  ... Incoming message from " + connection.ToString() + " saying '" + incomingString + "'.");
            });

            //Create suitable SSLOptions to use with TCP
            SelectSSLOptions();

            //Get a list of all local endPoints using the default port
            List <IPEndPoint> desiredlocalEndPoints = (from current in HostInfo.IP.FilteredLocalAddresses()
                                                       select new IPEndPoint(current, 0)).ToList();

            //Create a list of matching TCP listeners where we provide the listenerSSLOptions
            List <ConnectionListenerBase> listeners = (from current in desiredlocalEndPoints
                                                       select(ConnectionListenerBase)(new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions,
                                                                                                                ApplicationLayerProtocolStatus.Enabled,
                                                                                                                listenerSSLOptions))).ToList();

            //Start listening for incoming TCP connections
            Connection.StartListening(listeners, desiredlocalEndPoints, true);

            //Print out the listening addresses and ports
            Console.WriteLine("\nListening for incoming TCP (SSL) connections on:");
            foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            }

            //We loop here to allow any number of test messages to be sent and received
            while (true)
            {
                //Request a message to send somewhere
                Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):");
                string stringToSend = Console.ReadLine();

                //If the user has typed exit then we leave our loop and end the example
                if (stringToSend == "exit")
                {
                    break;
                }
                else
                {
                    //Once we have a message we need to know where to send it
                    //We have created a small wrapper class to help keep things clean here
                    ConnectionInfo targetServerConnectionInfo = ExampleHelper.GetServerDetails();

                    try
                    {
                        //Get a connection to the target server using the connection SSL options we configured earlier
                        //If there is a problem with the SSL handshake this will throw a CommsSetupShutdownException
                        TCPConnection connection = TCPConnection.GetConnection(targetServerConnectionInfo,
                                                                               sendingSendReceiveOptions,
                                                                               connectionSSLOptions);

                        //Send our message of the encrypted connection
                        connection.SendObject("Message", stringToSend);
                    }
                    catch (CommsException)
                    {
                        //We catch all exceptions by using CommsException
                        Console.WriteLine("\nERROR - Connection to " + targetServerConnectionInfo + " was unsuccessful." +
                                          " Server is either not listening or the entered SSL configurations" +
                                          "are not compatible. Please check settings and try again.");
                    }
                }
            }

            //If we have used comms features we must gracefully shutdown
            NetworkComms.Shutdown();
        }
Example #11
0
 private string CreateCrsCommand(string name, string keyname, CertificateDetails certificateDetails)
 {
     return("openssl req -config /root/ca/intermediate/openssl.cnf -key /root/ca/intermediate/private/" + keyname + ".key.pem " +
            CreateSubjectParameter(certificateDetails) + " " +
            "-new -sha256 -out /root/ca/intermediate/csr/" + name + ".csr.pem");
 }
Example #12
0
        public static void Start(IDataContext context)
        {
            Log.Info("Starting Server...");

            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) =>
            {
                if (errors == SslPolicyErrors.None)
                {
                    return(true);
                }

                var certificateDetails = new CertificateDetails(certificate);
                var thumbprint         = certificateDetails.Thumbprint;
                var exceptions         = context.GetRepository <CertificateException>();

                if (exceptions.Exist(x => x.Thumbprint == thumbprint))
                {
                    return(true);
                }

                Log.Error($"Invalid Certificate: {certificateDetails}");
                throw new OverseerException("certificate_exception", certificateDetails);
            };

            var settings = context.GetApplicationSettings();
            var endPoint = string.Format(EndPointFormatter, settings.LocalPort);

            WebApp.Start(endPoint, app =>
            {
                GlobalHost.DependencyResolver.Register(typeof(StatusHub), () => OverseerBootstrapper.Container.Resolve <StatusHub>());
                GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => OverseerBootstrapper.Container.Resolve <JsonSerializer>());

                app.UseOverseerAuthentication();

                app.MapSignalR("/push", new HubConfiguration
                {
                    EnableDetailedErrors    = true,
                    EnableJavaScriptProxies = true,
                    EnableJSONP             = false
                });

                app.Map("/api", a =>
                {
                    a.UseNancy(new NancyOptions {
                        Bootstrapper = new OverseerBootstrapper(context)
                    });
                });

                app.Use(RedirectToWebApp);

                app.UseFileServer(new FileServerOptions
                {
                    EnableDirectoryBrowsing = false,
                    EnableDefaultFiles      = true,
                    DefaultFilesOptions     = { DefaultFileNames = { "index.html" } },
                    FileSystem        = new PhysicalFileSystem(ClientPath),
                    StaticFileOptions = { ContentTypeProvider = new OverseerContentTypeProvider() }
                });
            });

            Log.Info($"Listening at {endPoint}...");
        }
Example #13
0
 public ConnectionCertItemViewModel(ConnectionViewModel pConnection, CertificateDetails pCertificate)
 {
     _connection = pConnection;
     Details     = pCertificate;
     UseCommand  = new BasicCommand(OnUseCert);
 }
Example #14
0
 public void Init()
 {
     instance = new CertificateDetails();
 }
Example #15
0
        public static void RunExample()
        {
            NetworkComms.ConnectionEstablishTimeoutMS = 600000;

            //Create a suitable certificate if it does not exist
            if (!File.Exists("testCertificate.pfx"))
            {
                CertificateDetails details = new CertificateDetails("CN=networkcomms.net", DateTime.Now, DateTime.Now.AddYears(1));
                SSLTools.CreateSelfSignedCertificatePFX(details, "testCertificate.pfx");
            }

            //Load the certificate
            X509Certificate cert = new X509Certificate2("testCertificate.pfx");

            IPAddress localIPAddress = IPAddress.Parse("::1");

            Console.WriteLine("Please select mode:");
            Console.WriteLine("1 - Server (Listens for connections)");
            Console.WriteLine("2 - Client (Creates connections to server)");

            //Read in user choice
            if (Console.ReadKey(true).Key == ConsoleKey.D1)
            {
                serverMode = true;
            }
            else
            {
                serverMode = false;
            }

            if (serverMode)
            {
                NetworkComms.AppendGlobalIncomingPacketHandler <byte[]>("Data", (header, connection, data) =>
                {
                    Console.WriteLine("Received data (" + data.Length + ") from " + connection.ToString());
                });

                //Establish handler
                NetworkComms.AppendGlobalConnectionEstablishHandler((connection) =>
                {
                    Console.WriteLine("Connection established - " + connection);
                });

                //Close handler
                NetworkComms.AppendGlobalConnectionCloseHandler((connection) =>
                {
                    Console.WriteLine("Connection closed - " + connection);
                });

                SSLOptions            sslOptions = new SSLOptions(cert, true, true);
                TCPConnectionListener listener   = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions,
                                                                             ApplicationLayerProtocolStatus.Enabled, sslOptions);
                Connection.StartListening(listener, new IPEndPoint(localIPAddress, 10000), true);

                Console.WriteLine("\nListening for TCP (SSL) messages on:");
                foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
                {
                    Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
                }

                Console.WriteLine("\nPress any key to quit.");
                ConsoleKeyInfo key = Console.ReadKey(true);
            }
            else
            {
                ConnectionInfo serverInfo = new ConnectionInfo(new IPEndPoint(localIPAddress, 10000));

                SSLOptions sslOptions = new SSLOptions("networkcomms.net", true);
                //SSLOptions sslOptions = new SSLOptions(cert, true);

                TCPConnection conn = TCPConnection.GetConnection(serverInfo, NetworkComms.DefaultSendReceiveOptions, sslOptions);
                conn.SendObject("Data", sendArray);
                Console.WriteLine("Sent data to server.");

                Console.WriteLine("\nClient complete. Press any key to quit.");
                Console.ReadKey(true);
            }

            NetworkComms.Shutdown();
        }