使用纯Lua实现HMAC-MD5算法。

我需要在纯 Lua 中编写一个 HMAC-MD5算法。。

我从 维基百科 得到了这个算法

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 // Whereis exclusive or (XOR)

    return hash(o_key_pad ∥ hash(i_key_pad ∥ message)) // Where '∥' is concatenation
end function

我已经从 这里 得到了 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 是 Stackoverflow 链接中的 md5.Calc 函数。

我卡在了计算 o_key_padi_key_pad 的部分上。我只需要对这两个值进行异或运算吗?维基百科链接中的 Python 实现有一些奇怪的计算,请帮帮我!

点赞
用户82294
用户82294

是的,"⊕" 是“异或”符号。

  • 记住:一旦计算最终哈希,请勿使用普通字符串比较来检查哈希是否正确。这将 允许攻击者签署任意消息

  • 请注意,0x5c * blocksize 可能不是你要查找的,因为它将 0x5c 乘以 blocksize。你想创建一个长度为 blocksize 的数组,每个位置都包含 0x5c

  • 请注意,你必须用零字节填充,而不是字符"0"。所以 key = key .. "0" 是错误的。它应该是 key = key .. "\0",或者在Lua中如何创建NUL字节。

2013-01-06 00:26:58