Ryan McClure
Ryan McClure

Reputation: 1223

Calculating k for padding of SHA-256 message

I'm implementing the SHS SHA-256 algorithm in VHDL and I am having trouble coming up with a way to solve the equation for k when padding the message with zeroes. The equation is outlined in the SHS description as follows:

Append the bit “1” to the end of the message, followed by k zero bits, where k is the smallest, non-negative solution to the equation l + 1 + k ≡ 448mod512.

I've seen the equation k = 448 - (l mod 512 + 1) which works if l mod 512 is less than or equal to 448, but if it is larger you get a negative number for k. I understand in this case we just need to append the "1", pad with "0"s until we hit 512, and then pad with 448 more zeroes followed by the 64 bit binary representation of the message length.

A similar question asked here is answered with an example:

Well, if l = 448 (say), the solution to the equation in the spec gives k = 511

I understand where 511 came from, but I can't figure out exactly how I can change the equation to get this number. Using the equation from above results in k = -1. I realize I could add 512 to the resultant k in the case that k is negative, and this will get me the right answer. However, I'd like to know if there is a single line equation that can avoid having to check for that.

Thanks!

Upvotes: 2

Views: 1840

Answers (1)

Ryan McClure
Ryan McClure

Reputation: 1223

I realized I can just add 512 to the rhs of the equation and then mod the entire thing by 512 as such:

k = (512 + 448 - (l mod 512 + 1)) mod 512

This takes care of the negative answer.

Upvotes: 1

Related Questions