0

I have a project that its main target is to create a shared space between two clients written in c# via a server written in python. The c# clients are written with the exact same code and the GUI forms synchronize by text messages that go through the server ( the server should be able to know how to read these messages in order to make sure that they are not "malicious" messages). In the clients I have singleton static class that is suppose to be responsible for all communication to the server. The server send it to the other client. This static class invokes a specific method in each form, this method process the input. For example, the message "0040mainForm /Mousemove 320 150" will be invoked to the form named mainForm, and will move the mouse to x=320 and y=150. In the server, before the clients establish the connection between them, each of them need to sign up, log in, and call to the other client. If the other client answers, the session will start.

I succeeded implement all this code and then my lecturer told me that I have to encrypt all messages that are being sent in web. I have tried at first with RSA encryption between the server and the client, but the decryption method didn't succeed to encrypt the encrypted text. I have tried later to use diffiehellman and then use it to transfer AES keys to establish symmetric encryption between the client and the server but it won't work too. At last I decided to encrypt only connection from first client destined to the second client (communication before session begins remain plain), I tried to transfer symmetric keys using diffiehellman too but it won't work too.

Can you help me find the appropriate and easiest way to encrypt those messages? * Before adding any cryptography thingies the code worked well. ** The symmetric encrypt method in the code didn't work. Receiving thread in the static class in c# that receive messages-

 public static void RecievingMessage()
        {
            if (srvr != null && openForms != null)
            {
                bool sent = true;
                int i = 0;
                int length = 0;
                string msg;
                string[] msg_array;
                if (srvr != null)
                    while (true)
                    {
                        Thread.Sleep(20);
                        byte[] fullData = new byte[4096];
                        int bytesRec = srvr.Receive(fullData);
                        string stringData = Encoding.ASCII.GetString(fullData);
                        length = int.Parse(string.Join("",stringData.Take(4).ToArray()));
                        sent = false;
                        if (talkingTo) // Value true when talking to server and false when to client.
                        {
                            byte[] data = fullData.Skip(4).Take(length).ToArray();
                            msg = Encoding.ASCII.GetString(data);
                        }
                        else
                        {
                            stringData = string.Join("", stringData.Skip(4).Take(length).ToArray());
                            byte[] data = Encoding.ASCII.GetBytes(stringData);
                            msg = SymmetricDecrypt(data, addresseeKey);
                        }
                        msg_array = msg.Split(' ');
                        for (i = 0; i < openForms.Count; i++)
                        {
                            if (msg_array[0].Equals(openForms[i].Name))
                            {

                                openForms[i].Recieve(msg_array);
                                sent = true;
                            }
                        }
                    }
            }

        }`

Sending a message method in the static class in client (c#)-

 public static void SendMessage(string sender, string message)
        {
            if (srvr != null)
            {
                i ++;
                try
                {
                    byte[] data = new byte[4096];
                    byte[] lengthOfData = new byte[4];
                    string data2 = sender + " " + message + " "; 
                    lengthOfData = GetDataLength(data2.Length);
                    if (talkingTo)
                    {
                        srvr.Send(CombineByteArrays(new byte[][] { lengthOfData, Encoding.ASCII.GetBytes(data2) }));
                    }
                    else
                    {
                        byte[] datatosend = SymmetricEncrypt(data2,addresseeKey);
                        srvr.Send(CombineByteArrays(new byte[][] { GetDataLength(datatosend.Length), datatosend }));
                    }
                }
                catch (SocketException e)
                {
                    Console.WriteLine("{0} Exception caught.", e);
                }
            }
        }

Encryption method - AES I think, (given key)-

public static byte[] SymmetricEncrypt(string plaintext, byte[] key)
         {
             using (Rijndael desObj = Rijndael.Create())
             {
                 desObj.Key = key;
                 desObj.Mode = CipherMode.CFB;
                 desObj.Padding = PaddingMode.PKCS7;
                 using (MemoryStream ms = new MemoryStream())
                 {
                     //Append the random IV that was generated to the front of the stream.
                     ms.Write(desObj.IV, 0, desObj.IV.Length);

                     //Write the bytes to be encrypted.
                     using (CryptoStream cs = new CryptoStream(ms, desObj.CreateEncryptor(), CryptoStreamMode.Write))
                     {
                         byte[] plainTextBytes = Encoding.ASCII.GetBytes(plaintext);
                         cs.Write(plainTextBytes, 0, plainTextBytes.Length);
                     }
                     return ms.ToArray();
                 }
             }
         }

Decryption method- AES too I think (given a key too)-

public static string SymmetricDecrypt(byte[] cyphertext, byte[] key)
     {
         using (MemoryStream ms = new MemoryStream(cyphertext))
         using (Rijndael desObj = Rijndael.Create())
         {
             desObj.Key = key;
             desObj.Mode = CipherMode.CFB;
             desObj.Padding = PaddingMode.PKCS7;

             //Read the IV from the front of the stream and assign it to our object.
             byte[] iv = new byte[16];
             int offset = 0;
             while (offset < iv.Length)
             {
                 offset += ms.Read(iv, offset, iv.Length - offset);
             }
             desObj.IV = iv;
             //Read the bytes to be decrypted
             using (CryptoStream cs = new CryptoStream(ms, desObj.CreateDecryptor(), CryptoStreamMode.Read))
             using (StreamReader sr = new StreamReader(cs, Encoding.ASCII))
             {
                 return sr.ReadToEnd();
             }
         }
     }

Only at the encrypting the messages between the clients part, after I gave up encrypting to the python server, I began using these two functions, (at the other tries I didn't even succeeded generate a key and transfer it). It showed me at first "Length of data to encrypt is invalid", then "Padding is invalid and can not be removed", then I tried to set padding to None and it returned to "Length of data to encrypt is invalid".

  • 1
    If it worked before adding `SymmetricEncrypt` and `SymmetricDecrypt`, you need to show those two functions. Also, you should show some example values along with errors and exceptions. – Artjom B. May 13 '17 at 14:26
  • @ArtjomB. Added. – Ofir Eizenberg May 13 '17 at 14:56
  • 1
    OK, your encryption and decryption looks fine. It's probably because you're storing arbitrary binary data in strings. Strings are not containers for binary data. Why don't you work on `byte[]` instead of converting the stuff you send or receive to `string`? – Artjom B. May 13 '17 at 15:48
  • Try with `Aes` instead of `Rijndael` – t.m.adam May 13 '17 at 16:12
  • @ArtjomB. I succeeded now to encrypt and decrypt using this solution: http://stackoverflow.com/a/10177020/5631525 , I generate the passPhrase using DiffieHellman method, do you think that this is secured enough? And, moreover, is it secured to not encrypt the conversation destined to the server (creating the session + logging in)? – Ofir Eizenberg May 13 '17 at 19:32

0 Answers0