I need a HMAC SHA implementation for Mathematica for an API authentication. I am not experienced at all in cryptography, hash functions, and HMAC. So far what I found is this:
hmac[key_, message_] :=
Module[{keyLen = StringLength[key], dkey, opad, ipad, blocksize = 64,
method = "SHA"},
dkey = If[keyLen > blocksize, IntegerString[Hash[key, method], 16],
StringPadRight[key, blocksize, FromCharacterCode[0]]]; {opad,
ipad} = FromCharacterCode[
BitXor[ToCharacterCode@
StringRepeat[FromCharacterCode[FromDigits[#, 16]], blocksize],
ToCharacterCode@dkey]] & /@ {"5c", "36"};
IntegerString[
Hash[StringJoin[opad,
ExportString[
IntegerDigits[Hash[StringJoin[ipad, message], method], 256],
"Binary"]], method], 16]]
But using the examples from Wikipedia, it returns wrong results. With
hmac["key", "The quick brown fox jumps over the lazy dog"]
I get the result: c0af2d1bc1449a4d4e239af0012d8d183d639fcc. The correct output should be de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9.
Could anyone on advise what is wrong? Also, what would be the modifications that I will need to turn this into SHA256 from SHA1?
hmacFnew["SHA1", "The quick brown fox jumps over the lazy dog", "key"]then you get the de7c9b85... result from Wikipedia. $\endgroup$