Question

I've hacked up some other code I've found thanks to SO. I'm not getting any errors when writing my encrypted data to disk, but I get an "index of bounds" error inside the RijndaelManaged class when reading data back.

This is my class I'm using to create a read and write stream wrapped with AES encryption (this is my actual salt, but I'll be sure to change it before release):

public class Crypto
{
    private static byte[] _salt = Encoding.ASCII.GetBytes("42kb$2fs$@#GE$^%gdhf;!M807c5o666");

    public static Stream CreateCryptoStreamAESWrite(string sharedSecret, Stream stream)
    {
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // generate the key from the shared secret and the salt
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

        // Create a RijndaelManaged object
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

        // Create a decryptor to perform the stream transform.
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        // prepend the IV
        stream.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
        stream.Write(aesAlg.IV, 0, aesAlg.IV.Length);

        CryptoStream csEncrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
        return csEncrypt;
    }

    public static Stream CreateCryptoStreamAESRead(string sharedSecret, Stream stream)
    {
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // generate the key from the shared secret and the salt
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

        // Create a RijndaelManaged object
        // with the specified key and IV.
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

        // Get the initialization vector from the encrypted stream
        aesAlg.IV = ReadByteArray(stream);

        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
        CryptoStream csDecrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
        return csDecrypt;
    }

    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");

        return buffer;
    }
}

Here is some test usage code I wrote:

        FileStream fs = new FileStream("c:\\temp\\test.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None);
        Stream cs = Crypto.CreateCryptoStreamAESWrite("test", fs);
        BinaryWriter bw = new BinaryWriter(cs);
        bw.Write("test");
        cs.Flush();
        fs.Close();
        fs = new FileStream("c:\\temp\\test.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        cs = Crypto.CreateCryptoStreamAESRead("test", fs);
        BinaryReader br = new BinaryReader(cs);
        string test = br.ReadString();
        if (test != "test")
            throw new Exception("Your Kungfu is not good!");
        fs.Close();

This is the error I get on the br.ReadString() line:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 out
putOffset, PaddingMode paddingMode, Boolean fLast)
   at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(
Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
   at System.Security.Cryptography.CryptoStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.Stream.ReadByte()
   at System.IO.BinaryReader.ReadByte()
Was it helpful?

Solution

Looks like I needed to call Close on my Crypto stream. I was calling Flush, but not Close. I replaced cs.Flush() with cs.Close() and now it is working.

Hopefully someone can at least learn from the example code in my question, although I imagine there is an easier way to just read/write AES encrypted streams (to/from file or otherwise).

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