umegaya/lua-aws — pull request #5 by umegaya (2014-10-16 21:02:04+00:00)
Title: fix sha2 bug

lua-aws sha2 routine (taken from http://lua-users.org/wiki/SecureHashAlgorithm) seems to have a problem in pre-processing when message length is 55 (mod 64) in bytes.

sha2 pre-processing is defined as below. (from definition of http://www.wikiwand.com/en/SHA-2 )

```
Pre-processing:
append the bit '1' to the message
append k bits '0', where k is the minimum number >= 0 such that the resulting message
length (modulo 512 in bits) is 448.
append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer
(this will make the entire post-processed length a multiple of 512 bits)
```

and here is implementation of pre-processing in [above page](http://lua-users.org/wiki/SecureHashAlgorithm)
``` lua
local function preproc (msg, len)
local extra = 64 - ((len + 1 + 8) % 64)
len = num2s(8 * len, 8) -- original len in bits, coded
msg = msg .. "\128" .. string.rep("\0", extra) .. len
```

if message length is 55 (mod 64), appending the bit '1' to the message ( appending "\128" in the code )
makes total message length 56 (mod 64), so no more zeroes need to append. but actually variable 'extra' become 64 in such a case. so unnecessary 512 bits '0' appended to message, which causes wrongly calculated sha2 hash value.