I need to write a HMAC-MD5 algorithm in pure Lua..
I got this algorithm from Wikipedia
function hmac (key, message)
if (length(key) > blocksize) then
key = hash(key) // keys longer than blocksize are shortened
end if
if (length(key) < blocksize) then
key = key ∥ [0x00 * (blocksize - length(key))] // keys shorter than blocksize are zero-padded ('∥' is concatenation)
end if
o_key_pad = [0x5c * blocksize] ⊕ key // Where blocksize is that of the underlying hash function
i_key_pad = [0x36 * blocksize] ⊕ key // Where ⊕ is exclusive or (XOR)
return hash(o_key_pad ∥ hash(i_key_pad ∥ message)) // Where '∥' is concatenation
end function
and I have the md5 code from here. The md5 calculation function works correctly..
Implementing the algorithm in lua, so far I have the following code
local function hmac_md5(key,msg)
local blocksize = 64
if string.len(key) > blocksize then
key = calculateMD5(key)
end
while string.len(key)<blocksize do
key = key .. "0"
end
-- local o_key_pad = bit_xor((0x5c * blocksize),key)
-- local i_key_pad = bit_xor((0x36 * blocksize),key)
return calculateMD5(o_key_pad..calculateMD5(i_key_pad..message))
end
--calculateMD5 is the md5.Calc function in the Stackoverflow link specifed
I am stuck in the part where o_key_pad and i_key_pad are calculated.. do I just XOR the 2 values? The python implementation in the wikipedia link had some weird calculations..
Please help!
Yes, “⊕” is the symbol for “exclusive or”.
Remember: once you compute the final hash, DO NOT use an ordinary string comparison to check if a hash is correct. This WILL allow attackers to sign arbitrary messages.
Note that
0x5c * blocksizeis probably not what you are looking for, since that multiplies0x5cbyblocksize. You want to create an array of lengthblocksizecontaining0x5cin each position.Note that you must pad with zero bytes, not the character
"0". Sokey = key .. "0"is wrong. It should bekey = key .. "\0", or however you create NUL bytes in Lua.