Reputation: 4515
To calculate the SHA-256 hash I need to pad my message. Am using the following description: (taken from http://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf)
Pad the message in the usual way: Suppose the length of the message M, in bits, is l. Append the bit "1" to the end of the message, and then k zero bits, where k is the smallest non-negative solution to the equation l+1+k 448 mod 512. To this append the 64-bit block which is equal to the number l written in binary
But what should one do if the message length in bits is less than 64-bits short of a 512bit block... i.e., there isn't room for the end 64-bit block mentioned above? Or the 64-bit length and the "1" bit?
I had a look on wikipedia too, but this doesn't throw any more light on the subject. Google searches haven't been too fruitful either, would appreciate any suggestions :)
Thanks
Upvotes: 4
Views: 6255
Reputation: 16
If you are implementing SHA-256 in bytes instead of bits, you can pad the byte 0x80
at the end of the last chunk. We use 0x80
because in binary it gives us 0b10000000
which is the same as one bit. After that, you just pad the rest of the bytes with 0x00
and you append the message length at the last 8 bytes of the last chunk. So if your message is abc
, so 3 bytes long, your last chunk's 8 bytes should be (in base 16):
00 00 00 00
00 00 00 18
Upvotes: 0
Reputation: 50104
If your message is only just short of a full block (less than 65 bits short), you will need your output to be a block longer than your input. In the worst case, if your message is exactly 64 bits short of a full block, you will add a 1
and then 511 0
s before the "number" bits, but that is how the padding has to work.
Upvotes: 5