【问题标题】:HMAC-MD5 in pure lua纯lua中的HMAC-MD5
【发布时间】: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()

标签: hash lua md5 hmac


【解决方案1】:

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

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

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

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

【讨论】:

  • 为什么不用普通的字符串比较?
  • @daurnimator:普通字符串比较允许攻击者在非常合理的假设和现实条件下签署任意消息。 NOT 使用普通字符串比较来进行签名检查,这会造成非常严重的安全漏洞。
  • 它是如何造成安全漏洞的?如果校验和中大约为空字节,则 lua 字符串以长度存储(除非所有字符都相等,否则不会比较相等)。
  • @daurnimator:它与 HMAC 中的 NUL 字节或结果无关。简单的字符串比较会泄漏有关两个字符串之间差异的信息。它以字符串比较的时间编码,根据字符串不同的位置,这需要不同的时间。要回答您的问题,是的,这在现实条件下是可以利用的。是的,它可以通过网络利用,即使存在延迟抖动。不,漏洞利用不会花费不合理的时间。是的,系统已经以这种方式受到了攻击。永远不要编写自己的加密库。
  • 好吧,不过对于 lua 来说仍然不是问题;字符串是实习的,并且总是一个单指针比较。
猜你喜欢
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多