How should the length field be handled in a cipher? Suppose that I have a chunked stream. Each chunk is to be encrypted separately. The structure is basically this:

([LEN][DATA])[MAC]([LEN][DATA])[MAC]([LEN][DATA])[MAC]...

How should one handle the LEN field? If I encrypt the whole thing in a (), this encrypts the LEN field as well. So at decrypt, LEN field must be first decrypted, to find out, where the MAC is. Which is considered a bad thing (as I found at several places that the recommendation is: "one should verify MAC before decryption").

The other solution, to pass LEN in cleartext, maybe not a good idea either, as I'd like to encrypt everything.

What's the correct solution for this problem?
It should not be possible to simply remove or add data to a value and come to a valid MAC for a specific key, without knowing the key value. So in that sense you can get away with moving the length out of the encryption.

It would be wise to MAC the length and ciphertext for your authentication tag (MAC value). If you'd be using an authenticated (AEAD) cipher you could put the length in the Additionally Authenticated Data (AAD) input for the cipher.

Generally the length of the plaintext can be easily retrieved or guessed from the ciphertext length; it is for instance identical in CTR mode (and therefore most authenticated modes as well). So in that sense specifying the length is not a security risk. If you want to keep the size secret you must pad the plaintext before using the encryption mode of operation.



Note that you should be aware that without an overall MAC it is possible for an attacker to swap chunks around in your scheme (!). You are also missing an IV value in your scheme, although you could simply count the chunks and use the counter. This would also solve the issue with the re-ordering (but not with truncation!).