Example #1
0
        public void TestPublic()
        {
            TextReader reader = new StringReader(OpenIdTestBase.LoadEmbeddedFile("dhpriv.txt"));

            try {
                string line;
                int    lineNumber = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    TestUtilities.TestLogger.InfoFormat("\tLine {0}", ++lineNumber);
                    string[]             parts = line.Trim().Split(' ');
                    byte[]               x     = Convert.FromBase64String(parts[0]);
                    DiffieHellmanManaged dh    = new DiffieHellmanManaged(AssociateDiffieHellmanRequest.DefaultMod, AssociateDiffieHellmanRequest.DefaultGen, x);
                    byte[]               pub   = dh.CreateKeyExchange();
                    byte[]               y     = Convert.FromBase64String(parts[1]);

                    if (y[0] == 0 && y[1] <= 127)
                    {
                        y.CopyTo(y, 1);
                    }

                    Assert.AreEqual(
                        Convert.ToBase64String(y),
                        Convert.ToBase64String(DiffieHellmanUtilities.EnsurePositive(pub)),
                        line);
                }
            } finally {
                reader.Close();
            }
        }
Example #2
0
        public void TestPublic()
        {
            StreamReader sr = new StreamReader(@"..\..\src\DotNetOpenId.Test\dhpriv.txt");

            try {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[]             parts = line.Trim().Split(' ');
                    byte[]               x     = Convert.FromBase64String(parts[0]);
                    DiffieHellmanManaged dh    = new DiffieHellmanManaged(DiffieHellmanUtil.DEFAULT_MOD, DiffieHellmanUtil.DEFAULT_GEN, x);
                    byte[]               pub   = dh.CreateKeyExchange();
                    byte[]               y     = Convert.FromBase64String(parts[1]);

                    if (y[0] == 0 && y[1] <= 127)
                    {
                        y.CopyTo(y, 1);
                    }

                    Assert.AreEqual(y, Convert.FromBase64String(DiffieHellmanUtil.UnsignedToBase64(pub)), line);
                }
            } finally {
                sr.Close();
            }
        }
Example #3
0
        /// <summary>
        /// Creates the association at the provider side after the association request has been received.
        /// </summary>
        /// <param name="request">The association request.</param>
        /// <param name="securitySettings">The security settings of the Provider.</param>
        /// <returns>The newly created association.</returns>
        /// <remarks>
        /// The response message is updated to include the details of the created association by this method,
        /// but the resulting association is <i>not</i> added to the association store and must be done by the caller.
        /// </remarks>
        protected override Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings)
        {
            ErrorUtilities.VerifyArgumentNotNull(request, "request");
            var diffieHellmanRequest = request as AssociateDiffieHellmanRequest;

            ErrorUtilities.VerifyArgument(diffieHellmanRequest != null, "request");
            ErrorUtilities.VerifyArgumentNotNull(securitySettings, "securitySettings");

            this.SessionType = this.SessionType ?? request.SessionType;

            // Go ahead and create the association first, complete with its secret that we're about to share.
            Association association = HmacShaAssociation.Create(this.Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, securitySettings);

            this.AssociationHandle = association.Handle;
            this.ExpiresIn         = association.SecondsTillExpiration;

            // We now need to securely communicate the secret to the relying party using Diffie-Hellman.
            // We do this by performing a DH algorithm on the secret and setting a couple of properties
            // that will be transmitted to the Relying Party.  The RP will perform an inverse operation
            // using its part of a DH secret in order to decrypt the shared secret we just invented
            // above when we created the association.
            DiffieHellman dh = new DiffieHellmanManaged(
                diffieHellmanRequest.DiffieHellmanModulus ?? AssociateDiffieHellmanRequest.DefaultMod,
                diffieHellmanRequest.DiffieHellmanGen ?? AssociateDiffieHellmanRequest.DefaultGen,
                AssociateDiffieHellmanRequest.DefaultX);
            HashAlgorithm hasher = DiffieHellmanUtilities.Lookup(this.Protocol, this.SessionType);

            this.DiffieHellmanServerPublic = DiffieHellmanUtilities.EnsurePositive(dh.CreateKeyExchange());
            this.EncodedMacKey             = DiffieHellmanUtilities.SHAHashXorSecret(hasher, dh, diffieHellmanRequest.DiffieHellmanConsumerPublic, association.SecretKey);

            return(association);
        }
        public DiffieHellmanKeyExchange(TlsContext ctx)
        {
            this.protocol = ctx.NegotiatedProtocol;

            switch (protocol)
            {
            case TlsProtocolCode.Tls12:
                Signature = new SignatureTls12(ctx.Session.ServerSignatureAlgorithm);
                break;

            case TlsProtocolCode.Tls10:
                Signature = new SignatureTls10();
                break;

            case TlsProtocolCode.Tls11:
                Signature = new SignatureTls11();
                break;

            default:
                throw new NotSupportedException();
            }

            dh = new DiffieHellmanManaged();
            Y  = dh.CreateKeyExchange();
            var dhparams = dh.ExportParameters(true);

            P = dhparams.P;
            G = dhparams.G;

            using (var buffer = CreateParameterBuffer(ctx.HandshakeParameters))
                Signature.Create(buffer, ctx.Configuration.PrivateKey);
        }
Example #5
0
        public override byte[] GetPublicKey()
        {
            DHParameters parameters = this.internalEncryptionObj.ExportParameters(false);

            return(Serializer <GladNetProtobufNetSerializer> .Instance
                   .Serialize(new DiffieHellmanWireContainer(parameters, internalEncryptionObj.CreateKeyExchange())));
        }
Example #6
0
    public Int32 GetSendSeed()
    {
        byte[]     data = enc_dh.CreateKeyExchange();
        BigInteger i    = new BigInteger(data);

        return(i % Int32.MaxValue);
    }
Example #7
0
    public Int32 GetReceiveSeed()
    {
        byte[]     data = dhDec.CreateKeyExchange();
        BigInteger i    = new BigInteger(data);

        return(i % Int32.MaxValue);
    }
Example #8
0
    public static void Main(string[] args)
    {
        // create a new DH instance
        DiffieHellman dh1 = new DiffieHellmanManaged();
        // export the public parameters of the first DH instance
        DHParameters dhp = dh1.ExportParameters(false);
        // create a second DH instance and initialize it with the public parameters of the first instance
        DiffieHellman dh2 = new DiffieHellmanManaged(dhp.P, dhp.G, 160);

        // generate the public key of the first DH instance
        byte[] ke1 = dh1.CreateKeyExchange();
        // generate the public key of the second DH instance
        byte[] ke2 = dh2.CreateKeyExchange();
        // let the first DH instance compute the shared secret using the second DH public key
        byte[] dh1k = dh1.DecryptKeyExchange(ke2);
        // let the second DH instance compute the shared secret using the first DH public key
        byte[] dh2k = dh2.DecryptKeyExchange(ke1);
        // print both shared secrets to verify they are the same
        Console.WriteLine("Computed secret of instance 1:");
        PrintBytes(dh1k);
        Console.WriteLine("\r\nComputed secret of instance 2:");
        PrintBytes(dh2k);

        Console.WriteLine("\r\nPress ENTER to continue...");
        Console.ReadLine();
    }
Example #9
0
        public void CreateNewSessionKey()
        {
            if (this.FinishedKeyExchange == false)
            {
                // The logic elsewhere is to call this method unless RemoteHasKey == true.
                // That needs to be cleaned up, because this is pointless.
                if (sentKeyExchange == true)
                {
                    //LogManager.Current.WriteToLog("CreateNewSessionKey() AGAIN for " + this.ToString() + "\n" + Environment.StackTrace);
                    return;
                }

                try {
                    Core.LoggingService.LogInfo("Creating secure communication channel to {0}...", this.ToString());

                    sentKeyExchange = true;

                    byte[]    keyExchange = diffieHellman.CreateKeyExchange();
                    Message   m           = network.MessageBuilder.CreateNewSessionKeyMessage(this, keyExchange);
                    AckMethod c           = new AckMethod();
                    c.args    = new object[] { this };
                    c.Method += new AckMethod.MethodEventHandler(network.NewSessionKeyReady);
                    network.AckMethods.Add(m.MessageID, c);
                    network.SendRoutedMessage(m);
                } catch (Exception ex) {
                    Core.LoggingService.LogError("Failed to create key exchange! Hopefully we will retry... " + ex.Message);
                    sentKeyExchange = false;
                    throw ex;
                }
            }
            else
            {
                Core.LoggingService.LogWarning("Why are we trying to CreateNewSessionKey for {0} when FinishedKeyExchange=True?", this.ToString());
            }
        }
Example #10
0
        public override KeyPair GenerateKeyPair()
        {
            DiffieHellmanManaged dh     = new DiffieHellmanManaged(pspec.P.GetBytes(), pspec.G.GetBytes(), 0);
            DHParameters         dhpars = dh.ExportParameters(true);
            BigInteger           y      = new BigInteger(dh.CreateKeyExchange());

            return(new KeyPair(new DHPrivateKey(dhpars), new DHPublicKey(y)));
        }
        public void should_create_a_key_exchange_when_providing_just_the_public_parameters()
        {
            var p = "23";
            _diffieHellmanManaged = new DiffieHellmanManaged(p, "5");
            var exchange = _diffieHellmanManaged.CreateKeyExchange();

            Assert.IsTrue(exchange.Length <= p.Length);
        }
 public override void GenerateClient(TlsContext ctx)
 {
     using (var dh = new DiffieHellmanManaged(P, G, 0)) {
         using (var X = new SecureBuffer(dh.DecryptKeyExchange(Y))) {
             Y = dh.CreateKeyExchange();
             ComputeMasterSecret(ctx, X);
         }
     }
 }
Example #13
0
        public void should_create_a_key_exchange_when_providing_just_the_public_parameters()
        {
            var p = "23";

            _diffieHellmanManaged = new DiffieHellmanManaged(p, "5");
            var exchange = _diffieHellmanManaged.CreateKeyExchange();

            Assert.IsTrue(exchange.Length <= p.Length);
        }
Example #14
0
        public static DHKeyPair GenerateKeyPair(int keysize)
        {
            DiffieHellman dh         = new DiffieHellmanManaged(_prime, new byte[] { 0x02 }, keysize);
            DHParameters  privateKey = dh.ExportParameters(true);

            return(new DHKeyPair(
                       new DHPrivateKey(privateKey),
                       new DHPublicKey(dh.CreateKeyExchange())));
        }
        public void should_create_a_key_exchange_when_all_parameters_are_provided()
        {
            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "6");
            var exchange = _diffieHellmanManaged.CreateKeyExchange();
            Assert.AreEqual("8", exchange);

            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "15");
            exchange = _diffieHellmanManaged.CreateKeyExchange();
            Assert.AreEqual("19", exchange);
        }
Example #16
0
        public void should_be_able_to_create_an_end_to_end_handshake()
        {
            var    diffieHellmanManaged1 = new DiffieHellmanManaged("23", "5");
            string exchange1             = diffieHellmanManaged1.CreateKeyExchange();

            var    diffieHellmanManaged2 = new DiffieHellmanManaged("23", "5");
            string exchange2             = diffieHellmanManaged2.CreateKeyExchange();

            Assert.IsTrue(diffieHellmanManaged1.DecryptKeyExchange(exchange2) == diffieHellmanManaged2.DecryptKeyExchange(exchange1));
        }
        public void should_be_able_to_create_an_end_to_end_handshake()
        {
            var diffieHellmanManaged1 = new DiffieHellmanManaged("23", "5");
            string exchange1 = diffieHellmanManaged1.CreateKeyExchange();

            var diffieHellmanManaged2 = new DiffieHellmanManaged("23", "5");
            string exchange2 = diffieHellmanManaged2.CreateKeyExchange();

            Assert.IsTrue(diffieHellmanManaged1.DecryptKeyExchange(exchange2) == diffieHellmanManaged2.DecryptKeyExchange(exchange1));
        }
Example #18
0
        public void should_create_a_key_exchange_when_all_parameters_are_provided()
        {
            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "6");
            var exchange = _diffieHellmanManaged.CreateKeyExchange();

            Assert.AreEqual("8", exchange);

            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "15");
            exchange = _diffieHellmanManaged.CreateKeyExchange();
            Assert.AreEqual("19", exchange);
        }
Example #19
0
        private void OnConnected(ITransport transport)
        {
            try {
                LoggingService.LogInfo("Transport {0} connected.", transport);

                if (transport.Encryptor != null)
                {
                    var dh = new DiffieHellmanManaged();

                    var keyxBytes = dh.CreateKeyExchange();
                    transport.Send(dh.CreateKeyExchange(), 0, keyxBytes.Length);

                    keyxBytes = new byte [transport.Encryptor.KeyExchangeLength];
                    transport.Receive(keyxBytes, 0, transport.Encryptor.KeyExchangeLength);

                    keyxBytes = dh.DecryptKeyExchange(keyxBytes);

                    var keyBytes = new byte[transport.Encryptor.KeySize];
                    var ivBytes  = new byte[transport.Encryptor.IvSize];
                    Array.Copy(keyxBytes, 0, keyBytes, 0, keyBytes.Length);
                    Array.Copy(keyxBytes, keyBytes.Length, ivBytes, 0, ivBytes.Length);

                    transport.Encryptor.SetKey(keyBytes, ivBytes);
                }

                var connectionType = EndianBitConverter.GetBytes(transport.ConnectionType);
                transport.Send(connectionType, 0, connectionType.Length);

                var networkId = Common.Utils.SHA512(transport.Network.NetworkName);
                transport.Send(networkId, 0, networkId.Length);

                // Ready, Steady, GO!

                var callback = connectCallbacks [transport];
                connectCallbacks.Remove(transport);
                callback(transport);
            } catch (Exception ex) {
                transport.Disconnect(ex);
                RaiseTransportError(transport, ex);
            }
        }
Example #20
0
        private static string Test1()
        {
            DiffieHellman dh1 = new DiffieHellmanManaged();
            DiffieHellman dh2 = new DiffieHellmanManaged();

            string secret1 = Convert.ToBase64String(dh1.DecryptKeyExchange(dh2.CreateKeyExchange()));
            string secret2 = Convert.ToBase64String(dh2.DecryptKeyExchange(dh1.CreateKeyExchange()));

            Assert.AreEqual(secret1, secret2, "Secret keys do not match for some reason.");

            return(secret1);
        }
        public void should_create_a_final_key_with_the_collaborators_key()
        {
            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "15");
            _diffieHellmanManaged.CreateKeyExchange();

            Assert.AreEqual("2", _diffieHellmanManaged.DecryptKeyExchange("8"));

            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "6");
            _diffieHellmanManaged.CreateKeyExchange();

            Assert.AreEqual("2", _diffieHellmanManaged.DecryptKeyExchange("19"));
        }
Example #22
0
        public void should_create_a_final_key_with_the_collaborators_key()
        {
            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "15");
            _diffieHellmanManaged.CreateKeyExchange();

            Assert.AreEqual("2", _diffieHellmanManaged.DecryptKeyExchange("8"));

            _diffieHellmanManaged = new DiffieHellmanManaged("23", "5", "6");
            _diffieHellmanManaged.CreateKeyExchange();

            Assert.AreEqual("2", _diffieHellmanManaged.DecryptKeyExchange("19"));
        }
Example #23
0
        void CreateServer(TlsContext ctx)
        {
            dh = new DiffieHellmanManaged();
            Y  = dh.CreateKeyExchange();
            var dhparams = dh.ExportParameters(true);

            P = dhparams.P;
            G = dhparams.G;

            using (var buffer = CreateParameterBuffer(ctx.HandshakeParameters))
                Signature = SignatureHelper.CreateSignature(SignatureAlgorithm, buffer, ctx.Configuration.PrivateKey);
        }
Example #24
0
    public static void Main(string[] args)
    {
        DiffieHellman diffieHellman  = new DiffieHellmanManaged();
        DHParameters  dHParameters   = diffieHellman.ExportParameters(includePrivate: false);
        DiffieHellman diffieHellman2 = new DiffieHellmanManaged(dHParameters.P, dHParameters.G, 160);

        byte[] keyEx  = diffieHellman.CreateKeyExchange();
        byte[] keyEx2 = diffieHellman2.CreateKeyExchange();
        byte[] bytes  = diffieHellman.DecryptKeyExchange(keyEx2);
        byte[] bytes2 = diffieHellman2.DecryptKeyExchange(keyEx);
        Console.WriteLine("Computed secret of instance 1:");
        PrintBytes(bytes);
        Console.WriteLine("\r\nComputed secret of instance 2:");
        PrintBytes(bytes2);
        Console.WriteLine("\r\nPress ENTER to continue...");
        Console.ReadLine();
    }
Example #25
0
        /// <summary>
        /// Генерация клиентского запроса с параметрами Диффи-Хеллмана
        /// </summary>
        /// <param name="serverDh"></param>
        /// <returns></returns>
        private Combinator SetClientDhParams(Combinator serverDh)
        {
            var g       = serverDh.Get <int>("g");
            var dhPrime = serverDh.Get <byte[]>("dh_prime");
            var gA      = serverDh.Get <byte[]>("g_a");

            var dh = new DiffieHellmanManaged(dhPrime, new BigInteger(g).GetBytes(), 2048);

            // generate the public key of the second DH instance
            byte[] gB = dh.CreateKeyExchange();
            // let the second DH instance compute the shared secret using the first DH public key
            _authKey = dh.DecryptKeyExchange(gA);

            // Сформируем ответ
            // отдаем g_b в BE
            var clientDhInnerData = new Combinator("client_DH_inner_data", _nonce, _serverNonce, (long)0, gB);

            byte[] s = clientDhInnerData.Serialize();

            // Шифрование строки
            var aes = new Aes256IgeManaged(CalculateTmpAesKey(_newNonce, _serverNonce)
                                           , CalculateTmpAesIV(_newNonce, _serverNonce));

            using (var ms = new MemoryStream())
                using (var bw = new BinaryWriter(ms))
                {
                    SHA1 sha1 = SHA1.Create();
                    bw.Write(sha1.ComputeHash(s));
                    bw.Write(s);

                    var r = new Random();
                    while (bw.BaseStream.Length % 16 != 0)
                    {
                        bw.Write((byte)r.Next());
                    }

                    s = aes.Encrypt(ms.ToArray());
                }

            // Сформируем ответ
            var setClientDhParams = new Combinator("set_client_DH_params", _nonce, _serverNonce, s);

            return(setClientDhParams);
        }
        public void KeyExchange()
        {
            // create a new DH instance
            DiffieHellman dh1 = new DiffieHellmanManaged();
            // export the public parameters of the first DH instance
            DHParameters dhp = dh1.ExportParameters(false);
            // create a second DH instance and initialize it with the public parameters of the first instance
            DiffieHellman dh2 = new DiffieHellmanManaged(dhp.P, dhp.G, 160);

            // generate the public key of the first DH instance
            byte[] ke1 = dh1.CreateKeyExchange();
            // generate the public key of the second DH instance
            byte[] ke2 = dh2.CreateKeyExchange();
            // let the first DH instance compute the shared secret using the second DH public key
            byte[] dh1k = dh1.DecryptKeyExchange(ke2);
            // let the second DH instance compute the shared secret using the first DH public key
            byte[] dh2k = dh2.DecryptKeyExchange(ke1);
            // both shared secrets are the same
            AssertEquals("Shared Secret", dh1k, dh2k);
        }
Example #27
0
        internal void Add(ITransport transport, TransportCallback connectCallback)
        {
            try {
                // XXX: This should be negotiated as part of the initial handshake.
                transport.Encryptor = new AESTransportEncryptor();

                transports.Add(transport);

                if (NewTransportAdded != null)
                {
                    NewTransportAdded(transport);
                }

                LoggingService.LogInfo($"Transport {transport} added");

                if (transport.Incoming)
                {
                    if (connectCallback != null)
                    {
                        throw new ArgumentException("You can only specify a ConnectCallback for outoging connections!");
                    }

                    if (transport.Encryptor != null)
                    {
                        var dh = new DiffieHellmanManaged();

                        var keyxBytes = new byte[transport.Encryptor.KeyExchangeLength];
                        transport.Receive(keyxBytes, 0, keyxBytes.Length);
                        keyxBytes = dh.DecryptKeyExchange(keyxBytes);

                        var keyBytes = new byte[transport.Encryptor.KeySize];
                        var ivBytes  = new byte[transport.Encryptor.IvSize];
                        Array.Copy(keyxBytes, 0, keyBytes, 0, keyBytes.Length);
                        Array.Copy(keyxBytes, keyBytes.Length, ivBytes, 0, ivBytes.Length);

                        keyxBytes = dh.CreateKeyExchange();
                        transport.Send(keyxBytes, 0, keyxBytes.Length);

                        transport.Encryptor.SetKey(keyBytes, ivBytes);
                    }

                    //Receive connection type, which is a ulong (8 bytes)
                    var responseBuffer = new byte[8];
                    transport.Receive(responseBuffer, 0, 8);
                    var connectionType = EndianBitConverter.ToUInt64(responseBuffer, 0);

                    // Recieve network ID (64 bytes)
                    responseBuffer = new byte[64];
                    transport.Receive(responseBuffer, 0, 64);
                    var networkId = EndianBitConverter.ToString(responseBuffer).Replace("-", "");

                    // Match to one of our known networks!
                    foreach (var network in core.Networks)
                    {
                        if (network.NetworkID == networkId)
                        {
                            transport.Network = network;
                        }
                    }

                    if (transport.Network == null)
                    {
                        throw new Exception($"Unknown network: {networkId}.");
                    }

                    transport.ConnectionType = connectionType;

                    if (connectionType == ConnectionType.NodeConnection)
                    {
                        var connection = new LocalNodeConnection(transport);
                        transport.Operation = connection;
                        transport.Network.AddConnection(connection);
                        connection.Start();
                    }
                    else if (connectionType == ConnectionType.TransferConnection)
                    {
                        core.FileTransferManager.NewIncomingConnection(transport);
                    }
                    else
                    {
                        throw new Exception($"Unknown connection type: {connectionType}.");
                    }
                }
                else
                {
                    if (connectCallback == null)
                    {
                        throw new ArgumentNullException(nameof(connectCallback));
                    }

                    connectCallbacks.Add(transport, connectCallback);

                    LoggingService.LogInfo("Transport {0} connecting...", transport);

                    TransportCallback callback = OnConnected;
                    transport.Connect(callback);
                }
            } catch (Exception ex) {
                transport.Disconnect(ex);
                RaiseTransportError(transport, ex);
            }
        }
Example #28
0
        public void Add(ITransport transport, TransportCallback connectCallback)
        {
            try {
                // XXX: This should be negotiated as part of the initial handshake.
                transport.Encryptor = new AESTransportEncryptor();

                transports.Add(transport);

                NewTransportAdded?.Invoke(this, new TransportEventArgs(transport));

                this.loggingService.LogInfo(String.Format("Transport {0} added", transport.ToString()));

                if (transport.Incoming == true)
                {
                    if (connectCallback != null)
                    {
                        throw new ArgumentException("You can only specify a ConnectCallback for outoging connections!");
                    }

                    if (transport.Encryptor != null)
                    {
                        DiffieHellmanManaged dh = new DiffieHellmanManaged();

                        byte[] keyxBytes = new byte[transport.Encryptor.KeyExchangeLength];
                        transport.Receive(keyxBytes, 0, keyxBytes.Length);
                        keyxBytes = dh.DecryptKeyExchange(keyxBytes);

                        byte[] keyBytes = new byte[transport.Encryptor.KeySize];
                        byte[] ivBytes  = new byte[transport.Encryptor.IvSize];
                        Array.Copy(keyxBytes, 0, keyBytes, 0, keyBytes.Length);
                        Array.Copy(keyxBytes, keyBytes.Length, ivBytes, 0, ivBytes.Length);

                        keyxBytes = dh.CreateKeyExchange();
                        transport.Send(keyxBytes, 0, keyxBytes.Length);

                        transport.Encryptor.SetKey(keyBytes, ivBytes);
                    }

                    //Receive connection type, which is a ulong (8 bytes)
                    byte[] responseBuffer = new byte[8];
                    transport.Receive(responseBuffer, 0, 8);
                    ulong connectionType = EndianBitConverter.ToUInt64(responseBuffer, 0);

                    // Recieve network ID (64 bytes)
                    responseBuffer = new byte[64];
                    transport.Receive(responseBuffer, 0, 64);
                    string networkId = EndianBitConverter.ToString(responseBuffer).Replace("-", "");

                    // Match to one of our known networks!
                    foreach (Network network in Core.Networks)
                    {
                        if (network.NetworkID == networkId)
                        {
                            transport.Network = network;
                        }
                    }

                    if (transport.Network == null)
                    {
                        throw new Exception(String.Format("Unknown network: {0}.", networkId));
                    }

                    transport.ConnectionType = connectionType;

                    if (connectionType == ConnectionType.NodeConnection)
                    {
                        LocalNodeConnection connection = new LocalNodeConnection(transport);
                        transport.Operation = connection;
                        transport.Network.AddConnection(connection);
                        connection.Start();
                    }
                    else if (connectionType == ConnectionType.TransferConnection)
                    {
                        this.fileTransferManager.HandleIncomingTransport(transport);
                    }
                    else
                    {
                        throw new Exception(String.Format("Unknown connection type: {0}.",
                                                          connectionType.ToString()));
                    }
                }
                else
                {
                    if (connectCallback == null)
                    {
                        throw new ArgumentNullException("connectCallback");
                    }

                    connectCallbacks.Add(transport, connectCallback);

                    this.loggingService.LogInfo("Transport {0} connecting...", transport);

                    TransportCallback callback = new TransportCallback(OnConnected);
                    transport.Connect(callback);
                }
            } catch (Exception ex) {
                transport.Disconnect(ex);
                RaiseTransportError(transport, ex);
            }
        }