4 Replies - 987 Views - Last Post: 30 July 2016 - 02:06 PM Rate Topic: -----

#1 matteke   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 100
  • Joined: 26-February 15

Cannot read byte array properly

Posted 30 July 2016 - 03:53 AM

Hi all,

I'm making a chat application with AES encryption, first i went with base64 strings like Convert.ToBase64String

But the decrypter always threw the error that its not a base64 string, so i dropped them and just went with strings, this is the encrypt function:

        public static string Encrypt256(string text)
        {
            string outStr = null;
            RijndaelManaged aesAlg = null;
            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("secret", 64);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(text);
                        }
                    }
                    outStr = Encoding.ASCII.GetString(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return outStr;
        }


And then I have my decrypt function:

public static string Decrypt256(string text)
        {
            RijndaelManaged aesAlg = null;
            string plaintext = null;
            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("secret", 64);            
                byte[] bytes = Encoding.ASCII.GetBytes(text);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    aesAlg = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    aesAlg.IV = ReadByteArray(msDecrypt); <-- error happens here
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            catch(Exception ex)
            {

            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return plaintext;
        }


And this is the function that throws the error:

private static byte[] ReadByteArray(Stream s)
        {
            byte[] rawLength = new byte[sizeof(int)];
            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
            {
                throw new SystemException("Stream did not contain properly formatted byte array");
            }

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
            {
                throw new SystemException("Did not read byte array properly"); <---this one
            }

            return buffer;
        }


I really have no clue why it cant read it properly

Thanks in advance

Is This A Good Question/Topic? 0
  • +

Replies To: Cannot read byte array properly

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Cannot read byte array properly

Posted 30 July 2016 - 04:25 AM

Since you're checking against the length of the stream and array, I'd start debugging by checking facts & assumptions.

30	    return outStr;//Breakpoint here.  What is the true length?
...
aesAlg.IV = ReadByteArray(msDecrypt); // <-- error happens here // What is the length of msDecrypt?

I'm going to guess your sizes don't match. I could be wrong but here's what I think I see
13	            msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
14	            msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
I think you're writing out a bunch of byte to the length of sizeof(int) THEN YOU'RE APPENDING some more after that.
Later when you read, you're only allocating enough for the sizeof(int)
byte[] rawLength = new byte[sizeof(int)];

You say "I don't know why it doesn't work." - I'm left wondering how much you're worked on basic but vital debugging skills.

See FAQ # 2 "How do I debug my program?"

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 6: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated July 2016
Spoiler

This post has been edited by tlhIn`toq: 30 July 2016 - 04:29 AM

Was This Post Helpful? 1
  • +
  • -

#3 matteke   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 100
  • Joined: 26-February 15

Re: Cannot read byte array properly

Posted 30 July 2016 - 05:10 AM

I know, i have to work on my debugging skills :/

But I found the error thanks to the breakpoint, what happened is: it encrypts the message, and then it adds the sender in plaintext, but the one that receives it tries to decrypt the plaintext too, which throws the error :P

So placing my call for encryption earlier fixed it and thanks for the links :)
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 7090
  • View blog
  • Posts: 24,092
  • Joined: 05-May 12

Re: Cannot read byte array properly

Posted 30 July 2016 - 12:15 PM

Also, that was a very poor decision to stop using base 64 as the encoding for the encrypted text. You do realize that the encrypted data can contain zeroes in it, right? You also realize that zeroes are used to denote end of string in C#, right?
Was This Post Helpful? 0
  • +
  • -

#5 matteke   User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 100
  • Joined: 26-February 15

Re: Cannot read byte array properly

Posted 30 July 2016 - 02:06 PM

Yes i know, but i stopped using them because i first thought that base64 was the problem, after fixing it i switched from string back to base64
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1