Padding can be expressed as follows:
- Append a bit of value 1.
- Append between 0 and 511 bits of value 0. The number of bits to append here must be such that the total length after padding is a multiple of 512.
- Append the encoding of the length of the message (not counting the padding bits). That encoding always has size exactly 64 bits.
So, if your input has size 448 bits, then:
- After adding the bit of value 1, you get a total length of 449 bits.
- You will need to add exactly 511 bits of value 0. Otherwise, the final length won't be a multiple of 512. With these extra 511 bits, length is now 960 bits.
- With the length encoding, size is now 960 + 64 = 1024, which is indeed a multiple of 512.
The padded input is then split into blocks of 512 bits, processed in due order.
The sentence in the RFC about a length exactly equal to 448 is meant to clarify the process, in that the extra bit of value 1 is always added. That bit is not optional.
Formally, MD5 takes as input a sequence of bits. However, in most situations, we only hash sequences of bytes. In other words, the input length will always be a multiple of 8. The padding process, when expressed with bytes, becomes:
- Append a byte of value
0x80
.
- Append between 0 and 63 bytes of value
0x00
. The number of bytes to append here must be such that the total length (in bytes) after padding is a multiple of 64.
- Append the encoding of the length of the message (not counting the padding bytes). That encoding always has size exactly 8 bytes. The length is expressed in bits, i.e. it is eight times larger than the length in bytes.
The padded input is then split into blocks of 64 bytes, processed in due order.
This padding procedure is exactly the same as the one defined for bits; it is just expressed here from a byte-oriented viewpoint.