【发布时间】:2013-01-06 08:26:58
【问题描述】:
我需要用纯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 实现有一些奇怪的计算.. 请帮忙!
【问题讨论】:
-
永远不要在循环中连接。对于您的代码,只需使用
string.rep()