# Is the 64-bits length of the original string padded as well in the MD5 hashfunction?

So, for example I have a string which binary value is exactly 512 - 64 bits long, so the binary conversion of the string does not have to be padded. So that means I have a string of 56 chars.

The binary equivalant of 56 is `00111000`, which is 64 - 8 short of 64 bits. How are the remaining bits filled? Are they padded as well?

This is what happens when padding the string:

The message is "padded" (extended) so that its length (in bits) is congruent to 448, modulo 512. That is, the message is extended so that it is just 64 bits shy of being a multiple of 512 bits long. Padding is always performed, even if the length of the message is already congruent to 448, modulo 512.

Padding is performed as follows: a single "1" bit is appended to the message, and then "0" bits are appended so that the length in bits of the padded message becomes congruent to 448, modulo 512. In all, at least one bit and at most 512 bits are appended.

from here.

However, in the same document, no clarification is given on the remaining 'empty' bits (512 - 56 * 8 - 8):

A 64-bit representation of b (the length of the message before the padding bits were added) is appended to the result of the previous step. In the unlikely event that b is greater than 2^64, then only the low-order 64 bits of b are used. (These bits are appended as two 32-bit words and appended low-order word first in accordance with the previous conventions.)

At this point the resulting message (after padding with bits and with b) has a length that is an exact multiple of 512 bits. Equivalently, this message has a length that is an exact multiple of 16 (32-bit) words. Let M[0 ... N-1] denote the words of the resulting message, where N is a multiple of 16.

I hope my question is understood?

My guess is that 64 - bits(`00111000`) 0's are padded in front of the 64bit representation of the length.

• I think you've got it backwards. You pad the message until you've got 64 bits left (mod 512). And ONLY THEN you fill those 64 bits with a the length of the message. – StackzOfZtuff Oct 3 '15 at 8:59
• Yes I got that, thanks for your reply though, however I don't know how to pad the length of the original string (which should be 64 bits). As the binary representation of 56 is `00111000` it is 56 bits short, how do I add those? Do I just add extra 0's in front of it? – Thomas W Oct 3 '15 at 9:09
• As mentioned, you pad to achieve 64n-8 bytes. Then add an 8-byte unsigned integer with the original input length in bits (shl 3, or perhaps *8) LSB first which completes the digested length 64n. What has to be said is that even if your original string is already 64n-8 bytes long, you still have to append full 64 bytes of padding to get a valid hash. I found bugged code that didn't do this. And that's how I found this question. – user49760 Aug 22 '18 at 14:13