如何使用HMAC SHA256?

use*_*069 9 sha256 hmac

根据我使用HMAC SHA256阅读的各种文档,我已经理解:

H(K XOR opad,H(K XOR ipad,text))其中H在我的情况下是SHA256.

但是,SHA256输入只有一个参数,即消息.而H(K,text)有两个输入.那么如何计算H(k,文本)?

我应首先使用k对文本进行编码,然后使用H(encoded_text),其中encoded_text将用作消息?

谢谢

Tim*_*tje 14

  • H()是你的加密哈希函数,在这种情况下是SHA256(),但也可以是MD5或其他;
  • K是你的预定关键
  • Text是要进行身份验证的消息
  • opad是外部填充(0x5c5c5c ... 5c5c,一个块长的十六进制常量)
  • ipad是内部填充(0x363636 ... 3636,一个块长的十六进制常量)
  • 然后HMAC(K,m)在数学上由

HMAC(K,m)= H((K + opad)∥H((K⊕ipad)∥m)).

  • blocksized由您的哈希函数决定(MD5将是64字节)
  • o_key_pad = [opad*blocksize]⊕键
  • i_key_pad = [ipad*blocksize]⊕键

你的结果将是:

H(o_key_pad || H(i_key_pad || TEXT))
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到一个很好的阅读:http: //timdinh.nl/index.php/hmac/

还有下面几乎看起来像我的伪代码:

function hmac (key, message)
    opad = [0x5c * blocksize] // Where blocksize is that of the underlying hash function
    ipad = [0x36 * blocksize]

    if (length(key) > blocksize) then
        key = hash(key) // Where 'hash' is the underlying hash function
    end if

    for i from 0 to length(key) - 1 step 1
        ipad[i] = ipad[i] XOR key[i]
        opad[i] = opad[i] XOR key[i]
    end for

    return hash(opad || hash(ipad || message)) // Where || is concatenation
end function
Run Code Online (Sandbox Code Playgroud)