Exemplo n.º 1
0
        public void OnPeerDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);

                string incoming = szData.Substring(0, szData.Length - 1);

                if (incoming.StartsWith("/file"))
                {
                    MessageBox.Show("receiving file");
                    //recieved file
                    //file infile = new file();

                    string infilemsg = incoming.Substring(5);
                    cryptor.rijn.Key = senderClient.sessionkey;
                    string infilepart = cryptor.DecryptMessage(infilemsg);
                    string[] infilefields = infilepart.Split(' ');
                    //infile.fileid = infilefields[0];
                    //infile.filesize = infilefields[1];
                    string concat = infilefields[2]+" "+infilefields[3]+" "+infilefields[4];
                    byte[] bytefile = System.Text.Encoding.ASCII.GetBytes(concat);
                    //infile.filedata = bytefile;

                    string filename = infilefields[0];
                    //infile.filename = filename;

                    //filelist.Add(infile);
                    FileStream fStream = new FileStream(filename, FileMode.CreateNew);

                    BinaryWriter bw = new BinaryWriter(fStream);

                    bw.Write(bytefile);

                    bw.Close();

                    fStream.Close();

                }
                else if (incoming.StartsWith("/req"))
                {
                    //MessageBox.Show("Give me a halelujah");
                    //recieved share request

                    //receive tickets and import them to a arraylist.
                    mytickets tickets = new mytickets();

                    //List<client> clientlist = new List<client>();

                    tickets.DecodeFromString(incoming.Substring(4));

                    if ((!rsaserver.VerifyData(tickets.ticketlist[0].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signFirst))
                            || (!rsaserver.VerifyData(tickets.ticketlist[0].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signSecond)))
                    {
                        MessageBox.Show("AS is not authentic!");

                    }
                    else
                    {
                        ASCIIEncoding ByteConverter = new ASCIIEncoding();
                        string originalData = ByteConverter.GetString(tickets.ticketlist[0].origSecond);
                        string[] origfields = originalData.Split(' ');

                        if (!rsa.ToXmlString(false).Equals(origfields[2]))
                        {
                            MessageBox.Show("This ticket is not mine!");
                        }
                        else
                        {
                            string destData = ByteConverter.GetString(tickets.ticketlist[0].origFirst);
                            string[] destfields = destData.Split(' ');
                            senderClient = new client();
                            senderClient.ip = destfields[0];
                            senderClient.port = destfields[1];
                            senderClient.publicKey = destfields[2];
                            senderClient.ticket = incoming.Substring(4);
                            //WaitForPeerData(); // gerek var mý ?

                        }

                    }

                }
                else if (incoming.StartsWith("/key"))
                {
                    //recieved shared key

                    string[] KeyFields = incoming.Substring(4).Split(' ');
                    rsapeer.FromXmlString(senderClient.publicKey);

                    if (!rsapeer.VerifyData(ToByteArray(KeyFields[0]), new SHA1CryptoServiceProvider(), ToByteArray(KeyFields[1])))
                    {
                        MessageBox.Show("Key is not authenticated by valid sender!");

                    }
                    else
                    {
                        byte[] SessionKey = rsa.Decrypt(ToByteArray(KeyFields[0]), true);
                        senderClient.sessionkey = SessionKey;

                    }

                }
                else if (incoming.StartsWith("/sndreq"))
                {
                    //file'i oku
                    string[] fields = incoming.Substring(7).Split(' ');

                    //receive tickets and import them to a arraylist.
                    mytickets tickets = new mytickets();

                    //List<client> clientlist = new List<client>();

                    tickets.DecodeFromString(fields[0]);

                    if ((!rsaserver.VerifyData(tickets.ticketlist[0].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signFirst))
                            || (!rsaserver.VerifyData(tickets.ticketlist[0].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[0].signSecond)))
                    {
                        MessageBox.Show("AS is not authentic!");

                    }
                    else
                    {

                        try
                        {

                            string fname = fields[1];
                            FileInfo fInfo = new FileInfo(fname);

                            long numBytes = fInfo.Length;

                            FileStream fStream = new FileStream(fname, FileMode.Open, FileAccess.Read);

                            BinaryReader br = new BinaryReader(fStream);

                            data = br.ReadBytes((int)numBytes);
                            br.Close();
                            fStream.Close();

                            MessageBox.Show("sending file piece back");
                            string functionID = "/pback";

                            string request = functionID + BytesToHex(data).Replace(" ", "");

                            //Object objData = request;

                            byte[] byData = System.Text.Encoding.ASCII.GetBytes(request);

                            //who to send?
                            Socket tempSoc;
                            //try
                            //{
                            string target = new ASCIIEncoding().GetString(tickets.ticketlist[0].origFirst);
                            string[] targetFields = target.Split(' ');
                            string ipStr = targetFields[0];
                            string portStr = targetFields[1];

                            UpdateControls(false);
                            // Create the socket instance
                            tempSoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                            // Cet the remote IP address
                            IPAddress ip = IPAddress.Parse(ipStr);
                            int iPortNo = System.Convert.ToInt16(portStr);
                            // Create the end point
                            IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
                            // Connect to the remote host

                            tempSoc.Connect(ipEnd);
                            if (tempSoc.Connected)
                            {

                                UpdateControls(true);
                                //Wait for data asynchronously

                            }
                            //}
                            //catch (SocketException se)
                            //{
                            //  string str;
                            //str = "\nConnection failed, is the server running?\n" + se.Message;
                            //MessageBox.Show(str);
                            //UpdateControls(false);

                            //}

                            if (tempSoc != null)
                            {
                                tempSoc.Send(byData);
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }
                    }
                }
                else if (incoming.StartsWith("/pback"))
                {
                    string filePartMsg = incoming.Substring(6);
                    byte[] filePartb = ToByteArray(filePartMsg);

                    string bconcat = System.Text.Encoding.ASCII.GetString(filePartb);

                    string[] infilefields = bconcat.Split(' ');

                    byte[] tempPart = ToByteArray(infilefields[0]);

                    SharedData partOftheSecretThatWeAreTryingToAcquire = new SharedData();
                    partOftheSecretThatWeAreTryingToAcquire.xi = System.Convert.ToInt64(infilefields[1]);
                    partOftheSecretThatWeAreTryingToAcquire.yi = System.Convert.ToInt64(infilefields[2]);

                    secretsFromOthers.Add(partOftheSecretThatWeAreTryingToAcquire);
                    partsFromOthers.Add(tempPart);

                    if (partsFromOthers.Count >= enoughParts)
                    {
                        Reconstruct();
                    }
                }

                // Continue the waiting for data on the Socket
                WaitForPeerData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
Exemplo n.º 2
0
        // This the call back function which will be invoked when the socket
        // detects any client writing of data on the stream
        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,
                                         0, iRx, chars, 0);
                System.String szData = new System.String(chars);

                string incoming = szData.Substring(0, szData.Length - 1);

                if (incoming.StartsWith("/rsaC"))
                {
            #if _SHOWMSG
                    MessageBox.Show("RSA public key received");
            #endif

                    string rsaKey = incoming.Substring(5);
                    string[] fields = rsaKey.Split(' ');

                    clientInfo tempclient = new clientInfo();
                    tempclient.ip = fields[0];
                    tempclient.port = fields[1];
                    tempclient.publicKey = fields[2];

                    if(!clientsList.Contains(tempclient)) clientsList.Add(tempclient);

                }
                else if (incoming.StartsWith("/bck"))
                {
                    //client wants to back up
                    //decide which parties to connect
                    //pseudo connections list.
                    string[] backupreq = incoming.Substring(4).Split(' ');

                    //client req = new client();
                    int clientnum = -1;
                    for (int i = 0; i < clientsList.Count; i++)
                    {
                        if (clientsList[i].ip.Equals(backupreq[0]))
                        {
                            if (clientsList[i].port.Equals(backupreq[1]))
                            {
                                clientnum = i;
                            }
                        }
                    }
                    if (clientnum == -1) MessageBox.Show("Backup Request from unauthenticated user");
                    else
                    {
                        //req = clientsList[clientnum];

                        clientsList[clientnum].files[0].fileID = backupreq[2];
                        clientsList[clientnum].files[0].filesize = System.Convert.ToInt32(backupreq[3]);

                        //first part of every ticket is same
                        string ticketData = clientsList[clientnum].ip + " " + clientsList[clientnum].port + " " + clientsList[clientnum].publicKey;

                        // Create a UnicodeEncoder to convert between byte array and string.
                        ASCIIEncoding ByteConverter = new ASCIIEncoding();
                        byte[] originalData = ByteConverter.GetBytes(ticketData);
                        byte[] signedData;

                        signedData = rsa.SignData(originalData, new SHA1CryptoServiceProvider());

                        for (int i = 0; i < clientsList.Count; i++)
                        {
                            //Ticket i = E(PRas, IPa + PUa) || E(PRas, IPb + PUb)

                            if (i != clientnum)
                            {
                                //second part of the ticket
                                string ticketSecondData = clientsList[i].ip + " " + clientsList[i].port + " " + clientsList[i].publicKey;

                                // Create a UnicodeEncoder to convert between byte array and string.
                                byte[] originalSecondData = ByteConverter.GetBytes(ticketSecondData);
                                byte[] signedSecondData;

                                signedSecondData = rsa.SignData(originalSecondData, new SHA1CryptoServiceProvider());

                                clientsList[clientnum].files[0].filetickets.AddToList(originalData, signedData, originalSecondData, signedSecondData);

                            }
                        }

                        //sends them to the client
                        try
                        {
                            string functionID = "/tck";
                            string strTickets = clientsList[clientnum].files[0].filetickets.EncodeToString();

                            //TODO: somehow concatanate the message header; functionID
                            string TicketListMsg = functionID + strTickets; //tickets

                            byte[] byData2 = System.Text.Encoding.ASCII.GetBytes(TicketListMsg);

                            if (m_workerSocket[clientnum] != null)
                            {
                                if (m_workerSocket[clientnum].Connected)
                                {
                                    m_workerSocket[clientnum].Send(byData2);
                                }
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }

                    }

                    //mytickets tickets = new mytickets();

                    //clients[] clientsList = new clients[5];
                    //for (int i = 0; i < 5; i++)
                    //{
                    //    clientsList[i].ip = i * 100;
                    //    clientsList[i].port = i * 1000;
                    //    clientsList[i].publicKey = (i * 10000).ToString();
                    //}

                }
                else if (incoming.StartsWith("/rcv"))
                {
                    //client wants to recover
                    //decide which parties to connect
                    //pseudo connections list.
                    string[] recoverreq = incoming.Substring(4).Split(' ');

                    //client req = new client();
                    int clientnum = -1;
                    int filenum = -1;
                    for (int i = 0; i < clientsList.Count; i++)
                    {
                        if (clientsList[i].ip.Equals(recoverreq[0]))
                        {
                            if (clientsList[i].port.Equals(recoverreq[1]))
                            {
                                for (int j = 0; j < MAX_FILE; j++)
                                {
                                    if (clientsList[i].files[j].fileID != null)
                                    {
                                        if (clientsList[i].files[j].fileID.Equals(recoverreq[2]))
                                        {
                                            clientnum = i;
                                            filenum = j;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (clientnum == -1) MessageBox.Show("User nor authenticated!");
                    else if (filenum == -1) MessageBox.Show("File not in database!");
                    else
                    {
                        //req = clientsList[clientnum];
                        mytickets RecoveryTickets = new mytickets();
                        bool enoughFound = false;
                        for (int i = 0; !enoughFound && i < clientsList[clientnum].files[filenum].filetickets.ticketlist.Count; i++)
                        {

                            string possibleStorage = new ASCIIEncoding().GetString(clientsList[clientnum].files[filenum].filetickets.ticketlist[i].origSecond);
                            string[] fields = possibleStorage.Split(' ');
                            string possibleStorageIP = fields[0];
                            string possibleStoragePort = fields[1];
                            for (int j = 0; j < m_clientCount; j++)
                            {
                                if (m_workerSocket[j] != null)
                                {
                                    if (m_workerSocket[j].Connected)
                                    {
                                        if (possibleStorageIP.Equals(clientsList[j].ip))
                                        {
                                            if (possibleStoragePort.Equals(clientsList[j].port))
                                            {
                                                RecoveryTickets.AddToList(clientsList[clientnum].files[filenum].filetickets.ticketlist[i]);
                                                if (RecoveryTickets.ticketlist.Count >= clientsList[clientnum].files[filenum].filetickets.ticketlist.Count - 1)
                                                    enoughFound = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //sends them to the client
                        try
                        {
                            string functionID = "/rectck";
                            string strTickets = RecoveryTickets.EncodeToString();

                            //TODO: somehow concatanate the message header; functionID
                            string TicketListMsg = functionID + strTickets; //tickets

                            byte[] byData2 = System.Text.Encoding.ASCII.GetBytes(TicketListMsg);

                            if (m_workerSocket[clientnum] != null)
                            {
                                if (m_workerSocket[clientnum].Connected)
                                {
                                    m_workerSocket[clientnum].Send(byData2);
                                }
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }
                    }
                }
                else
                {
                    tb_encRecv.Enabled = true;
                    tb_encRecv.Text = BytesToHex(Convert.FromBase64String(szData.Substring(0, szData.Length - 1)));
                    string decryptedText = cryptor.DecryptMessage(szData.Substring(0, szData.Length - 1));
                    richTextBoxReceivedMsg.Text = decryptedText + "\n" + richTextBoxReceivedMsg.Text;

                }

                // Continue the waiting for data on the Socket
                WaitForData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
Exemplo n.º 3
0
        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
                int iRx = theSockId.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.Default.GetDecoder();
                int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
                System.String szData = new System.String(chars);

                string incoming = szData.Substring(0, szData.Length - 1);

                if (incoming.StartsWith("/chg"))
                {
            #if _SHOWMSG
                    MessageBox.Show("Mode Change Code recieved");
            #endif

                    string mode = incoming.Substring(4, 1);
                    cryptor.rijn.Mode = (CipherMode)Convert.ToInt32(mode);
                    tb_currentMode.Text = cryptor.rijn.Mode.ToString();

                }
                else if (incoming.StartsWith("/sIV"))
                {
            #if _SHOWMSG
                    MessageBox.Show("New IV recieved");
            #endif

                    string iv = incoming.Substring(4);
                    cryptor.rijn.IV = ToByteArray(iv);
                    tb_IV.Text = BytesToHex(cryptor.rijn.IV);
                }
                else if (incoming.StartsWith("/rsaS"))
                {
            #if _SHOWMSG
                    MessageBox.Show("RSA public key received");
            #endif

                    string rsaKey = incoming.Substring(5);

                    rsaserver = new RSACryptoServiceProvider(2048);
                    rsaserver.FromXmlString(rsaKey);

                    RSAParameters rsap = rsaserver.ExportParameters(false);

                    tb_RsaPublicKey.Text = BytesToHex(rsap.Modulus);
                    tb_RsaPublicKeyExpo.Text = BytesToHex(rsap.Exponent);

                    // do not need begin
                    cryptor.rijn.GenerateKey();
                    tb_aesKey.Text = BytesToHex(cryptor.rijn.Key);
                    byte[] rsaEncData = rsaserver.Encrypt(cryptor.rijn.Key, true);
                    string encKeyHex = BytesToHex(rsaEncData).Replace(" ", "");
                    tb_encKey.Text = encKeyHex;
                    //do not need end

                    string newKeyMsg = "/rsaC" + GetIP() + " " + myport + " " + rsa.ToXmlString(false);

                    try
                    {

                        Object objData = newKeyMsg;
                        byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                        if (m_clientSocket != null)
                        {

                            m_clientSocket.Send(byData);

                        }
                    }
                    catch (SocketException se)
                    {
                        MessageBox.Show(se.Message);
                    }

                }
                else if (incoming.StartsWith("/tck"))
                {
                    //recieved tickets

                    //receive tickets and import them to a arraylist.
                    mytickets tickets = new mytickets();
                    List<client> clientlist = new List<client>();

                    tickets.DecodeFromString(incoming.Substring(4));
                    int dest_count = tickets.GetClientCount();
                    for (int i = 0; i < dest_count; i++)
                    {
                        if ((!rsaserver.VerifyData(tickets.ticketlist[i].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signFirst))
                            || (!rsaserver.VerifyData(tickets.ticketlist[i].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signSecond)))
                        {
                            MessageBox.Show("AS is not authentic!");

                        }
                        else
                        {
                            ASCIIEncoding ByteConverter = new ASCIIEncoding();
                            string originalData = ByteConverter.GetString(tickets.ticketlist[i].origFirst);
                            string[] origfields = originalData.Split(' ');

                            if (!rsa.ToXmlString(false).Equals(origfields[2]))
                            {
                                MessageBox.Show("This ticket is not mine!");
                            }
                            else
                            {
                                string destData = ByteConverter.GetString(tickets.ticketlist[i].origSecond);
                                string[] destfields = destData.Split(' ');
                                client tempclient = new client();
                                tempclient.ip = destfields[0];
                                tempclient.port = destfields[1];
                                tempclient.publicKey = destfields[2];
                                tempclient.ticket = tickets.ExportSingleTicket(i);
                                clientlist.Add(tempclient);
                            }

                        }

                    }

                    int numParts = dest_count - 1; //because the final part is the parity

                    int lengthofEachPart = (int)(data.Length / numParts) + 1;//pad the last one

                    //hash = BitConverter.ToString(cryptoTransformSHA1.ComputeHash()).Replace("-", "");

                    List<byte[]> parts = new List<byte[]>();
                    for (int i = 0; i < numParts; i++)
                    {
                        byte[] temp = new byte[lengthofEachPart];

                        for (int j = 0; j < lengthofEachPart; j++)
                        {
                            if (i == numParts - 1 && i * lengthofEachPart + j >= data.Length) //padding
                            {
                                temp[j] = 0x00000000;
                            }
                            else
                            {
                                temp[j] = data[i * lengthofEachPart + j];
                            }
                        }

                        parts.Add(temp);
                    }

                    //we have the parts, calculate the parity part
                    byte[] parityPart = new byte[lengthofEachPart];

                    for (int j = 0; j < lengthofEachPart; j++)
                    {
                        byte xor = new byte();
                        xor = 0 ^ 0;
                        for (int i = 0; i < numParts; i++)
                        {
                            byte[] temp = (byte[])parts[i];
                            xor ^= temp[j];
                        }
                        parityPart[j] = xor;
                    }

                    parts.Add(parityPart);

                    //encrypt all parts with per file key
                    Random rand = new Random();
                    long randomNumToGenerateKey = rand.Next() % 25000;

                    byte[] randomNumToGenerateKeyByteEquivalent = new ASCIIEncoding().GetBytes(randomNumToGenerateKey.ToString());
                    perFileKey = cryptoTransformSHA1.ComputeHash(randomNumToGenerateKeyByteEquivalent);

                    byte[] reducedperfilekey = new byte[16];
                    for (int k = 0; k < 16; k++)
                    {
                        reducedperfilekey[k] = perFileKey[k];
                    }
                    cryptor.rijn.Key = reducedperfilekey;
                    for (int i = 0; i < numParts+1; i++)
                    {
                        string tempPart = cryptor.EncryptMessage(BytesToHex(parts[i]).Replace(" ", ""));
                        parts[i] = new ASCIIEncoding().GetBytes(tempPart);
                    }

                    //create the key and, secret share it with (n-1,n) threshold scheme.

                    ShamirSS sham = new ShamirSS((uint)parts.Count, (uint)parts.Count - 1, 25000);//burasý oldu lakin, reconstruct etmek c*k zor. GF(2^8) kullanmak lazým en azýndan

                    SharedData[] shamirOut = sham.ShareData(randomNumToGenerateKey);
                    //connect to each ticket granted user to send its assigned part
                    //out of scope

                    // TODO ticketlarý gönder herkese
                    //rsapeer = new RSACryptoServiceProvider(2048);
                    for (int i = 0; i < dest_count; i++)
                    {
                        try
                        {
                            UpdateControls(false);
                            // Create the socket instance
                            m_peerSockets[m_peerCount] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                            // Cet the remote IP address
                            IPAddress ip = IPAddress.Parse(clientlist[i].ip);
                            int iPortNo = System.Convert.ToInt16(clientlist[i].port);
                            // Create the end point
                            IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
                            // Connect to the remote host
                            m_peerSockets[m_peerCount].Connect(ipEnd);
                            if (m_peerSockets[m_peerCount].Connected)
                            {

                                UpdateControls(true);
                                //Wait for data asynchronously
                                WaitForPeerData(m_peerSockets[m_peerCount]);//????
                                m_peerCount++;

                            }
                        }
                        catch (SocketException se)
                        {
                            string str;
                            str = "\nConnection failed, is the peer online?\n" + se.Message;
                            MessageBox.Show(str);
                            UpdateControls(false);
                        }
                        if (m_peerSockets[m_peerCount - 1].Connected)
                        {
                            try
                            {
                                string functionID = "/req";

                                string request = functionID + clientlist[i].ticket;

                                //Object objData = request;

                                byte[] byData = System.Text.Encoding.ASCII.GetBytes(request);

                                if (m_peerSockets[m_peerCount - 1] != null)
                                {

                                    m_peerSockets[m_peerCount - 1].Send(byData);
                                }
                            }
                            catch (SocketException se)
                            {
                                MessageBox.Show(se.Message);
                            }
                        }
                        else
                            MessageBox.Show("shit load");

                        // TODO: Ks yarat encrypt et yolla
                        cryptor.rijn.GenerateKey();
                        client temp = new client();
                        temp = clientlist[i];
                        temp.sessionkey = cryptor.rijn.Key;
                        clientlist[i] = temp;
                        tb_aesKey.Text = BytesToHex(cryptor.rijn.Key);
                        rsapeer.FromXmlString(clientlist[i].publicKey);
                        byte[] rsaEncData = rsapeer.Encrypt(cryptor.rijn.Key, true);
                        byte[] rsaSigned;
                        rsaSigned = rsa.SignData(rsaEncData, new SHA1CryptoServiceProvider());
                        string rsaSignedEncHex = BytesToHex(rsaEncData).Replace(" ", "") + " " + BytesToHex(rsaSigned).Replace(" ", "");
                        tb_encKey.Text = rsaSignedEncHex;
                        try
                        {
                            string functionID = "/key";

                            string request = functionID + rsaSignedEncHex;

                            //Object objData = request;

                            byte[] byData = System.Text.Encoding.ASCII.GetBytes(request);

                            if (m_peerSockets[m_peerCount - 1] != null)
                            {

                                m_peerSockets[m_peerCount - 1].Send(byData);
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }

                        System.Threading.Thread.Sleep(50);
                        try
                        {
                            MessageBox.Show("sending file parts");
                            string functionID = "/file";

                            string filepart = hash + " " + data.Length.ToString() + " " + BytesToHex(parts[i]).Replace(" ", "");
                            filepart += " " + shamirOut[i].xi.ToString() + " " + shamirOut[i].yi.ToString();

                            string filemsg = cryptor.EncryptMessage(filepart);

                            string request = functionID + filemsg;

                            //Object objData = request;

                            byte[] byData = System.Text.Encoding.ASCII.GetBytes(request);

                            if (m_peerSockets[m_peerCount - 1] != null)
                            {

                                m_peerSockets[m_peerCount - 1].Send(byData);
                            }
                        }
                        catch (SocketException se)
                        {
                            MessageBox.Show(se.Message);
                        }

                    }

                }
                else if (incoming.StartsWith("/rectck"))
                {
                    //recieved tickets

                    //receive tickets and import them to a arraylist.
                    mytickets tickets = new mytickets();
                    List<client> clientlist = new List<client>();

                    tickets.DecodeFromString(incoming.Substring(7));
                    int dest_count = tickets.GetClientCount();
                    enoughParts = dest_count;
                    for (int i = 0; i < dest_count; i++)
                    {
                        if ((!rsaserver.VerifyData(tickets.ticketlist[i].origFirst, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signFirst))
                            || (!rsaserver.VerifyData(tickets.ticketlist[i].origSecond, new SHA1CryptoServiceProvider(), tickets.ticketlist[i].signSecond)))
                        {
                            MessageBox.Show("AS is not authentic!");

                        }
                        else
                        {
                            ASCIIEncoding ByteConverter = new ASCIIEncoding();
                            string originalData = ByteConverter.GetString(tickets.ticketlist[i].origFirst);
                            string[] origfields = originalData.Split(' ');

                            if (!rsa.ToXmlString(false).Equals(origfields[2]))
                            {
                                MessageBox.Show("This ticket is not mine!");
                            }
                            else
                            {
                                string destData = ByteConverter.GetString(tickets.ticketlist[i].origSecond);
                                string[] destfields = destData.Split(' ');
                                client tempclient = new client();
                                tempclient.ip = destfields[0];
                                tempclient.port = destfields[1];
                                tempclient.publicKey = destfields[2];
                                tempclient.ticket = tickets.ExportSingleTicket(i);
                                clientlist.Add(tempclient);
                            }

                        }

                    }

                    //partsFromOthers = new List<byte[]>();
                    for (int i = 0; i < clientlist.Count; i++)
                    {
                        //send tickets
                        //generate and send key
                        //send me the file
                        // TODO ticketlarý gönder herkese
                        try
                        {
                            UpdateControls(false);
                            // Create the socket instance
                            m_peerSockets[m_peerCount] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                            // Cet the remote IP address
                            IPAddress ip = IPAddress.Parse(clientlist[i].ip);
                            int iPortNo = System.Convert.ToInt16(clientlist[i].port);
                            // Create the end point
                            IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
                            // Connect to the remote host
                            m_peerSockets[m_peerCount].Connect(ipEnd);
                            if (m_peerSockets[m_peerCount].Connected)
                            {

                                UpdateControls(true);
                                //Wait for data asynchronously
                                WaitForPeerData(m_peerSockets[m_peerCount]);//????
                                m_peerCount++;

                            }
                        }
                        catch (SocketException se)
                        {
                            string str;
                            str = "\nConnection failed, is the peer online?\n" + se.Message;
                            MessageBox.Show(str);
                            UpdateControls(false);
                        }
                        if (m_peerSockets[m_peerCount - 1].Connected)
                        {
                            try
                            {
                                string functionID = "/sndreq";

                                string request = functionID + clientlist[i].ticket + " " + hash;

                                //Object objData = request;

                                byte[] byData = System.Text.Encoding.ASCII.GetBytes(request);

                                if (m_peerSockets[m_peerCount - 1] != null)
                                {

                                    m_peerSockets[m_peerCount - 1].Send(byData);
                                }
                            }
                            catch (SocketException se)
                            {
                                MessageBox.Show(se.Message);
                            }
                        }
                        else
                            MessageBox.Show("shit load");

                    }

                }

                else
                {
                    //decrypt message
                    tb_encRecv.Enabled = true;
                    tb_encRecv.Text = BytesToHex(Convert.FromBase64String(szData.Substring(0, szData.Length - 1)));
                    string decryptedText = cryptor.DecryptMessage(szData.Substring(0, szData.Length - 1));
                    richTextRxMessage.Text = decryptedText + "\n" + richTextRxMessage.Text;
                }

                WaitForData();
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }