hash - 纯lua中的HMAC-MD5

标签 hash lua md5 hmac

我需要用纯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/

相关文章:

c# - 可以使用缓冲读取计算 MD5(或其他)哈希值吗?

encryption - 创建加密 API key 的最佳方法

c# - 系统字典实现说明?

java - 当我尝试在 HashMap 中输入新 key 时,如何计算比较次数?

windows - 环境的 Lua 注册表?

Lua - 在 32 位 lua 编译器上处理 64 位数字

PHP pack() 函数的 Java 等效项

ruby - 如何按值对哈希数组进行排序?

hash - 会合与一致散列

objective-c - iPhone 上的 Lua-Objective-C 桥