0

I have a .jpg file of 10,174,706 bytes on the server and after i send it to the client i get 10,190,848 bytes as a multiple of 16 * 1024 (that what i used in CopyTo function for streams) which is more. No problem for a jpg file but i want to send a zip file or DLL file i think even 1 extra byte can corrupt the file. Are the extra bytes a problem for zip or DLL and exe files? And if they are a problem how to i fix this issue?


SERVER:

  case "Requestx64File":
            {
                Console.WriteLine("Text is a x64file request");
                using (var netStream = new NetworkStream(current))
                {
                    using (var fileStream = File.OpenRead("plm.jpg"))
                    {
                        fileStream.CopyTo(netStream);
                    }
                }

CopyTo Extension:

public static void CopyTo(this Stream input, Stream output)
    {
        byte[] buffer = new byte[16 * 1024];
        int bytesRead;

        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            byte[] secret_buffer = CryptosystemChiper.EncryptToByteArray(buffer);
            int size = secret_buffer.Length;
            output.Write(secret_buffer, 0, size);

        }
    }

CLIENT:

else if (lastMessageReceived.IndexOf("IncomingPayloadInfo") > -1)
    {
        ResponseParser rp = new ResponseParser(lastMessageReceived);


        using (NetworkStream netstream = new NetworkStream(ClientSocket))
        {
            using (var filestream = File.OpenWrite("plm.jpg"))
            {
                netstream.CopyTo(filestream);

            }
        }

    }

CopyTo Extension

public static void CopyTo(this Stream input, Stream output)
    {
        byte[] buffer = new byte[16 * 1024];
        int bytesRead;

        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            byte[] clear_buffer = CryptosystemChiper.DecryptToByteArray(buffer);
            int size = clear_buffer.Length;
            output.Write(clear_buffer, 0, size);
        }
        return;
    }

CryptosystemChiper for both CLIENT and SERVER:

    public class CryptosystemChiper
{
    static string EncryptionKey;



    public static void setKey(string key)
    {
        EncryptionKey = key;
    }
    #region Crypto
    //------------------------------------------------------------------------------------------------------------------------------------------------> Encryption/Decryption
    public static string EncryptToString(string clearText)
    {
        try
        {
            // string EncryptionKey = "MAKV2SPBNI99212"; //Encryption key
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); //Bytes of the message
            using (Aes encryptor = Aes.Create()) //Create a new AES decryptor
            {

                encryptor.KeySize = 128;
                encryptor.Padding = PaddingMode.Zeros;

                //Encrypt the data
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText; //Return the encrypted text
        }
        catch (Exception) //Something went wrong
        {
            //  ReportError(ErrorType.ENCRYPT_DATA_CORRUPTED, "Can't encrypt message!", "Message encryption failed!"); //Report error to server
            return clearText; //Send the plain text data
        }
    }


    /// <summary>
    /// Decrypt encrypted data
    /// </summary>
    /// <param name="cipherText">The data to decrypt</param>
    /// <returns>The plain text message</returns>
    public static string DecryptToString(string cipherText)
    {
        try
        {
            //string EncryptionKey = "MAKV2SPBNI99212"; //this is the secret encryption key  you want to hide dont show it to other guys
            byte[] cipherBytes = Convert.FromBase64String(cipherText); //Get the encrypted message's bytes
            using (Aes encryptor = Aes.Create()) //Create a new AES object
            {
                encryptor.KeySize = 128;
                encryptor.Padding = PaddingMode.Zeros;

                //Decrypt the text
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText; //Return the plain text data
        }
        catch (Exception ex) //Something went wrong
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("Cipher Text: " + cipherText);

            return "error"; //Return error
        }
    }

    public static byte[] EncryptToByteArray(byte[] clearBytes)
    {
        byte[] da = { 0 };
        byte[] ecnryptedBytes;
        try
        {
            // string EncryptionKey = "MAKV2SPBNI99212"; //Encryption key
            // byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); //Bytes of the message
            using (Aes encryptor = Aes.Create()) //Create a new AES decryptor
            {
                encryptor.KeySize = 128;
                encryptor.Padding = PaddingMode.Zeros;

                //Encrypt the data
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    ecnryptedBytes = ms.ToArray();
                }
            }

            return ecnryptedBytes; //Return the encrypted text
        }
        catch (Exception ex) //Something went wrong
        {
            ecnryptedBytes = null;
            //  ReportError(ErrorType.ENCRYPT_DATA_CORRUPTED, "Can't encrypt message!", "Message encryption failed!"); //Report error to server
            return ecnryptedBytes; //Send the plain text data
        }
    }

    /// <summary>
    /// Decrypt encrypted data
    /// </summary>
    /// <param name="cipherBytes">The data to decrypt</param>
    /// <returns>The plain text message</returns>
    public static byte[] DecryptToByteArray(byte[] cipherBytes)
    {
        byte[] clearBytes;
        try
        {
            //string EncryptionKey = "MAKV2SPBNI99212"; //this is the secret encryption key  you want to hide dont show it to other guys
            // byte[] cipherBytes = Convert.FromBase64String(cipherText); //Get the encrypted message's bytes

            using (Aes encryptor = Aes.Create()) //Create a new AES object
            {

                encryptor.KeySize = 128;
                encryptor.Padding = PaddingMode.Zeros;

                //Decrypt the bytes
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    clearBytes = ms.ToArray();
                }
            }
            return clearBytes; //Return the plain text data
        }
        catch (Exception ex) //Something went wrong
        {
            clearBytes = null;
            Console.WriteLine(ex.Message);
            Console.WriteLine("Cipher Text: " + clearBytes);

            return clearBytes; //Return error
        }
    }


    //------------------------------------------------------------------------------------------------------------------------------------------------> Encryption/Decryption
    #endregion
}`enter code here`
Rares Andrei
  • 81
  • 1
  • 10
  • 1
    You aren't ever using your `bytesread` variable. You need to check the value and use it to "crop" the buffer for non-full reads. It might be 16*1024 or it might be 1 or it might be 2139. You need to handle all cases – pinkfloydx33 Jun 13 '20 at 22:16
  • @pinkfloydx33 i used it to see the value changes before and after encryption, but if i "crop" the extra bytes won't i risk to corrupt the file given the fact that it would be a dll or exe? I could try this and update here if it works – Rares Andrei Jun 14 '20 at 09:22
  • You have tagged this question "Cryptography". Is the file encrypted? Are the extra bytes cryptographic padding? Alternatively, are they what was at the end of the transfer buffer when the last incomplete buffer-full was transferred? Can you check of the extra bytes match the end of the last-but-one buffer full transferred? – rossum Jun 14 '20 at 11:05
  • @rossum yes i checked. Before each buffer because i send it in chunks is 16384 bytes in bytearray after encryption i have 16400 bytes -> when i receive the buffer on the other side and decrypt it goes from 16400 bytes back to 16384 per chunk so it should go back to it's original state. Thing is I can't debug all of the chunks because client gets stuck after one loop and somehow manages to get all the file with the extra bytes (maybe because i keep the streams open but for now i think of a way to close the streams without closing the connection) – Rares Andrei Jun 15 '20 at 15:01

0 Answers0