I hope this is the right forum; I was not sure what I should ask about it in stackoverflow, cryptography or security.
So my problem is that the php hash_hmac function is only available with php> = 5.1.2. Since some servers are not upgraded to this version, I wrote my own HMAC implementation based on the php hash function. But the code does not produce the same output as hash_hmac ...
So where is my mistake?
define("HASH_ALGO", "sha512"); define("HMAC_BLOCKSIZE", 64); function computeHMAC($message, $key) { $ikey; $okey; $zero = hex2bin("00"); $ipad = hex2bin("36"); $opad = hex2bin("5C"); /* * HMAC construction scheme: * $ikey = $key padded with zeroes to blocksize and then each byte xored with 0x36 * $okey = $key padded with zeroes to blocksize and then each byte xored with 0x5C * hash($okey . hash($ikey . $message)) */ //Hash key if it is larger than HMAC_BLOCKSIZE if (strlen($key) > HMAC_BLOCKSIZE) { $key = hash(HASH_ALGO, $key, true); } //Fill ikey with zeroes for ($i = 0; $i < HMAC_BLOCKSIZE; $i++) { $ikey[$i] = $zero; } //Fill ikey with the real key for ($i = 0; $i < strlen($key); $i++) { $ikey[$i] = $key[$i]; } //Until they get xored both keys are equal $okey = $ikey; //Xor both keys for ($i = 0; $i < HMAC_BLOCKSIZE; $i++) { $ikey[$i] ^= $ipad; $okey[$i] ^= $opad; } //Build inner hash $innerHash = hash(HASH_ALGO, $ikey . $message, true); //Build outer hash $outerHash = hash(HASH_ALGO, $okey . $innerHash, true); return $outerHash; }
The function was tested with the following code:
echo hexDump(computeHMAC("Testolope", "Testkeyolope")); echo hexDump(hash_hmac(HASH_ALGO, "Testolope", "Testkeyolope", true)); The output is the following: HexDump (64 Bytes): 65 a8 81 af 49 f2 49 c5 64 7a 7a b7 a6 ac a0 4e 9e 9b 1a 3c 76 fc 48 19 13 33 e0 f8 82 be 48 52 1a 50 49 09 1e fe bf 94 63 5f 9d 36 82 3f 2f a1 43 b4 60 9f 9f e5 d1 64 c6 5b 32 22 45 07 c9 cb HexDump (64 Bytes): d2 e9 52 d2 ab f0 db a7 60 e0 52 b0 5c 23 5a 73 d9 8c 78 8e 9e fb 26 82 54 7e f9 c8 f1 65 df 7f 97 44 fe 2b 1e 2b 6d d5 cb a4 ba c6 73 35 06 9c 0f c8 2d 36 8c b3 9b c4 48 01 5c c2 9f ce b4 08
source share