Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HMAC implementation failure

Tags:

php

hash

hmac

I hope this is the right forum; I was not sure if I should ask this in stackoverflow, cryptography or security.

So my problem is that php's hash_hmac function is only available with php >=5.1.2. Because some servers are not updated to this version I wrote my own HMAC-implementaion based on php's hash function. But the code doesn't 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 
like image 724
K. Biermann Avatar asked Nov 01 '22 16:11

K. Biermann


1 Answers

The problem is that you've mixed up the digest size and block size; SHA-512 has a digest size of 64, but a block size of 128.

Secondly, both $ikey and $okey are arrays and not strings, so you need to convert them both into a string first:

$innerHash = hash(HASH_ALGO, join($ikey) . $message, true);
$outerHash = hash(HASH_ALGO, join($okey) . $innerHash, true);

That said, both hash() and hash_hmac() are documented as being available since 5.1.2, so I'm not sure what this will achieve :)

like image 129
Ja͢ck Avatar answered Nov 14 '22 02:11

Ja͢ck