Question

I'm trying to do a hmac hash of some hex bytes in php. Not sure if I understand the hash or hex representation correctly as the 2 hashes do not match up, e.g.

<?php
echo bin2hex("\x32\x45\xff\xca".pack("N",1))."\n";
echo hash_hmac('sha1', '\x32\x45\xff\xca\x00\x00\x00\x01', 'secret')."\n";
echo hash_hmac('sha1', '\x32\x45\xff\xca'.pack("N",1), 'secret')."\n";

gives

3245ffca00000001
3710e984df2fe4c53e0a9760cf0480357c6e431c
6308db257308f3466430807eb622489c7fff84df

The bytes seem to be the same to me yet they give a different hash...

Was it helpful?

Solution

Guess what, turns out what I needed was to use double quotes instead of single and both those hashes for '\x32\x45\xff\xca\x00\x00\x00\x01' are incorrect.

so

echo hash_hmac('sha1', "\x32\x45\xff\xca\x00\x00\x00\x01", 'secret')."\n";
echo hash_hmac('sha1', "\x32\x45\xff\xca".pack("N",1), 'secret')."\n";

gives the correct thing

cde1e3710b6265b77fd4ac84293e20d981e92a6a
cde1e3710b6265b77fd4ac84293e20d981e92a6a

Subtle but true, test it out here

OTHER TIPS

This is because in your input:

      echo hash_hmac('sha1', '\x32\x45\xff\xca\x00\x00\x00\x01', 'secret')."\n";
      echo hash_hmac('sha1', '\x32\x45\xff\xca'.pack("N",1), 'secret')."\n";

the strings which are to be hash_hmacd are different,

     echo '\x32\x45\xff\xca\x00\x00\x00\x01'; // output : \x32\x45\xff\xca\x00\x00\x00\x01
     echo '\x32\x45\xff\xca'.pack("N",1);     // output : \x32\x45\xff\xca

that's why your answer is coming up different.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top