# SHA256: Padding a 512 bits length message

I am currently implementing the SHA256 hash-algorithm for a "custom-built" embeded-device. Obviously I have a problem with message padding. The routine I wrote does not work with message whose size equals exactly 512 bits.

In that case, how should the message be padded ? i.e.

M = "AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPAABBCCDDEEFFGGHHIIJJKKLLMMNNOOPP"


I mean, what should be the hexa-decimal representation of the last padded block?

• You add 512 bits of padding. 0x80 in the first byte and the length is the last 8 bytes. Pretty much the same as for other messages. What's trickier is when less than 9 bytes remain in a block, since then you need to split the padding between two blocks. – CodesInChaos Oct 14 '15 at 20:14
• In the example above, I would add 0x200 for the length of the message so ? – Zyend Oct 14 '15 at 21:05
• Depends on the encoding, but I count 32 characters. For ASCII compatible that would be 0x100, not 0x200 – Maarten Bodewes Oct 15 '15 at 9:08

## 1 Answer

Any message that is 448 bits or larger is padded beyond the block size, and runs a second iteration of the compression function. If messages beyond this limit excluding intervals of 512 bits seem to work correctly, it is probably a simple math error. If it was an endianness issue, all lengths greater than 1 would fail.

I assume you are using a byte oriented approach to the design, therefore the padding byte [80] starts the first block, followed by [00] valued bytes, followed by the 64-bit length [0000000000000200], making the block look like this:

80 000000000000000000000000000000000000000000000 0000000000000200

• His message is 32 characters. That doesn't tell the byte size of course, so your answer would be valid for UTF-16 I suppose (64 * 8 = 512 = 200h). And you confuse bits and bytes. – Maarten Bodewes Oct 15 '15 at 9:03
• Sorry, I have edited my post above and the message is 64 bytes / 512 bits length. In my implementation, I made a mistake when copying the bytes of the 64 bits message length at the end of the block. – Zyend Oct 15 '15 at 9:36
• @Zyend OK, glad you got it solved. It was bound to be an implementation mistake I guess. – Maarten Bodewes Oct 15 '15 at 15:36