我需要用纯Lua编写一个HMAC-MD5算法..
我得到了这个算法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
我有来自 here 的 md5 代码。 md5计算函数工作正常..
在lua中实现该算法,到目前为止我有以下代码
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
我陷入了计算 o_key_pad 和 i_key_pad 的部分..我是否只对 2 个值进行异或?维基百科链接中的Python实现有一些奇怪的计算。 请帮忙!
最佳答案
是的,“⊕”是“异或”的符号。
请记住:计算最终哈希值后,请勿使用普通字符串比较来检查哈希值是否正确。这将允许攻击者签署任意消息。
请注意,
0x5c * blocksize
可能不是您要查找的内容,因为它将0x5c
乘以blocksize
。您想要创建一个长度为blocksize
的数组,每个位置都包含0x5c
。请注意,您必须用零字节填充,而不是字符
“0”
。所以key = key .. "0"
是错误的。它应该是key = key .. "\0"
,或者您在 Lua 中创建 NUL 字节。
关于hash - 纯lua中的HMAC-MD5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14177928/