0

I am in the process of writing a small encoding class which takes a byte[] array, and cyphers it. As the IV can be made public, I wish to prepend it to the ciphertext to use for decryption.

Following the MSDN Documentation and some SO Post source (Cant find link), I started the stream with the raw IV;

//Start encryption process
        using (var msEncrypt = new MemoryStream())
        {
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                using (var swWriter = new StreamWriter(csEncrypt))
                {

                    //Write all data to the stream.
                    swWriter.Write(encryptor.IV);
                    swWriter.Write(plainTextRaw);



                }

            }

            Console.WriteLine("Encrypted Value: {0}", BitConverter.ToString(msEncrypt.ToArray()).Replace("-", String.Empty));
            return msEncrypt.ToArray();

        }

However, upon writing a simple unit test extracting the first 16 bytes, they do not seem to match.

I am certain the IV is being encrypted within the stream, so where is the best place to inject it?

Daniel Park
  • 3,903
  • 4
  • 23
  • 38

1 Answers1

1

Just write the IV tot the initial memory stream msEncrypt, not to the stream that is being encrypted swWriter.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • I did this after thinking about the problem a little bit more. The unit tests written for the key encoding/retrieval now pass. Thanks for the answer. – Daniel Park Nov 17 '13 at 06:43
  • Yeah, sorry about the timing. Normally I follow the [tag:encryption] and [tag:cryptography] tags. For questions about either, I would recommend using one of those tags instead of [tag:rijndaelmanaged]. The last one is more precise but it has 2 followers in total at the time of writing... – Maarten Bodewes Nov 17 '13 at 20:17