public byte[] EncryptData(byte[] data, int length)
{
// if the length is greater than 4080 (after encryption, pads to 4096), we will have to cut it up
// so that our frame counter (1 byte) works
int consumed = 0;
MemoryStream stream = new MemoryStream();
int count = 0;
do
{
int consume = length - consumed > 4080 ? 4080 : length - consumed;
// Encrypt the data and add the IV
var encryptedData = Util.getSingleton().AesEncryptBytes(data, consumed, consume, _key);
consumed += consume;
// Now we need to prepend the length (always divisible by 16, so we can cheat and use a byte which
// still gives us a max buffer size of 255*16)
// encLength (number of hextets - 16 (IV) - 16 (first frame))
var encLength = (byte)((encryptedData.Length - 32) / 16);
// Now construct the final array which ultimately includes 1 byte length, 16 byte IV and unknown length
// encrypted message (but guaranteed >= 16)
// note, for this encLength to be useful, you will need to add 2 then times by 16
stream.WriteByte(encLength);
stream.Write(encryptedData, 0, encryptedData.Length);
count++;
} while (length > consumed);
#if DEBUG
//Logger.Debug("Encrypted " + length + " bytes into " + count + " frames");
#endif
return stream.ToArray();
}