Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top