Does including the size of the hashed data improve security over just the hash Trying to settle a discussion at work. We are mostly concerned with pre-image resistance.

Suppose we have a common secure hash function $H$ (e.g. SHA-1/SHA-2) and some message $M$ we want to hash. The message has length $M_L$. For the message we provide the digest $D$ and the length of data digested $D_L$.

With regards to preimage-resistance, for which common hash functions is it more secure to check that

$H(M) = D$ $and$ $M_L = D_L$

rather than just checking

$H(M) = D$

?
First the obvious; checking $M_L=D_L$:


is unnecessary from a security standpoint IF $H$ really is secure, by definition of that; but who knows what's really secure?
can't harm preimage resistance (first or/and second), nor collision resistance;
can greatly increase speed, if the hash is computed only after checking $M_L=D_L$; that's a common reason to perform this test in file de-duplication;
can harm the conceivable objective of hiding $D_L$ in some attack scenarios (such as timing or other side-channel attack);
harms even so slightly a common objective: simplicity.


It is possible to construct a devious $H$ that is collision resistant and second preimage resistant only if it is also checked $M_L=D_L$; e.g., a variant of SHA-256 that matches the original for messages of length $l\ge255$ bits; and for shorter messages outputs the original message, a one bit, and $255-l$ zero bit(s). That can be improved to a hash that is very secure from the standpoint of second preimage resistance if $M_L=D_L$ is checked, and less secure (according to some parameter) otherwise. That's indicative checking $M_L=D_L$ could help security for some otherwise insecure hashes.

If we take MD5 as an example: we know how to create collisions with little effort (including for messages with different and arbitrary beginning), but that's only if these messages have exactly the same length. Otherwise, the best known attack is brute force (feasible, but never performed publicly as of today for being too expensive). However that applies to collision-resistance, not to the question's preimage resistance (neither first nor second). Thus, in the case of MD5, we know that adding a check that $M_L=D_L$ does not significantly improves collision resistance, but MD5 remains preimage resistant without that check.



Definitions used:


first preimage resistance: given some arbitrary value the size of a hash, it is difficult to find a message with that hash.
second preimage resistance: given some arbitrary message, it is difficult to find a different message with the same hash.
collision resistance: it is difficult to find two distinct messages with the same hash.