コード例 #1
0
        public void StartComunication(string address)
        {
            if (this.HostAddress.Equals(address))
            {
                return;
            }
            if (clientSessions.ContainsKey(address))
            {
                PrintMessage.Print(string.Format("You are already connected to client: {0}", address));
                return;
            }

            NetTcpBinding binding = new NetTcpBinding();

            binding.SendTimeout    = new TimeSpan(0, 5, 5);
            binding.ReceiveTimeout = new TimeSpan(0, 5, 5);
            binding.OpenTimeout    = new TimeSpan(0, 5, 5);
            binding.CloseTimeout   = new TimeSpan(0, 5, 5);
            IClientContract serverProxy = new ClientProxy(new EndpointAddress(address), binding, this);

            byte[]      sessionKey = RandomGenerateKey();
            SessionData sd         = new SessionData()
            {
                AesAlgorithm = new AES128_ECB(sessionKey), Proxy = serverProxy, Address = address
            };

            CertificateDto serverCert = serverProxy.SendCert(new CertificateDto(myCertificate, false));

            if (!vaProxy.isCertificateValidate(serverCert.GetCert(false)))
            {
                PrintMessage.Print("Starting communication failed!");
                return;
            }

            byte[] encryptedSessionKey = null;
            try
            {
                RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)serverCert.GetCert(false).PublicKey.Key;

                if (publicKey != null)
                {
                    encryptedSessionKey = publicKey.Encrypt(sessionKey, true);
                }
                else
                {
                    PrintMessage.Print("Error, public key is null");
                    return;
                }
            }
            catch (Exception e)
            {
                PrintMessage.Print(string.Format("Error: {0}", e.Message));
            }
            bool success = serverProxy.SendKey(encryptedSessionKey);

            if (success)
            {
                sqliteWrapper.InsertToTable(sd.Address);

                object sessionInfo = serverProxy.GetSessionInfo(HostAddress);
                if (sessionInfo != null)
                {
                    string   sessionId      = System.Text.Encoding.UTF8.GetString(sd.AesAlgorithm.Decrypt((byte[])sessionInfo)).Trim();
                    string[] sessionIdSplit = sessionId.Split('|');
                    sd.CallbackSessionId = sessionIdSplit[0];
                    sd.ProxySessionId    = sessionIdSplit[1];
                    lock (objLock)
                    {
                        clientSessions.Add(sd.Address, sd);
                        PrintMessage.Print("Session is opened");
                    }
                }
            }
            else
            {
                PrintMessage.Print("Starting communication failed!");
            }
        }