How to use HMAC SHA256?
hmac, sha256
Solution
- H() is your cryptographic hash function, in this case SHA256() but could also be MD5 or whatever;
- K is your predifined key
- Text is the message to be authenticated
- opad be the outer padding (0x5c5c5c…5c5c, one-block-long hexadecimal constant)
- ipad be the inner padding (0x363636…3636, one-block-long hexadecimal constant)
- Then HMAC(K,m) is mathematically defined by
HMAC(K,m) = H((K ⊕ opad) ∥ H((K ⊕ ipad) ∥ m)).
- blocksized is determined by your hash function (MD5 would be 64 bytes)
- o_key_pad = [opad * blocksize] ⊕ key
- i_key_pad = [ipad * blocksize] ⊕ key
Your result would be:
H(o_key_pad || H(i_key_pad || TEXT))
You can find a good read here: http://timdinh.nl/index.php/hmac/
With also the following pseudocode which almost looks like mine :
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
Problem
As per the various docs that I have read for using HMAC SHA256, I have understood that: H (K XOR opad, H (K XOR ipad, text)) where H in my case is SHA256. But, SHA256 input has only one parameter i.e a Message. Whereas H(K,text) has two inputs. So how to calculate H(k,text)? Should I first encode text with k and then use H(encoded_text), where encoded_text will be used as a message? Thank You