Search code examples
phphmacsha1

How to set the hmacsha1 key to hex in PHP?


I'm able to successfully get a HMAC SHA1 signature key using the following code:

echo hash_hmac('sha1','office:fred','AA381AC5E4298C23B3B3333333333333333333');

which yields:

5e50e6458b0cdc7ee534967d113a9deffe6740d0

However, the place I am working with is expecting this instead:

46abe81345b1da2f1a330bba3d6254e110cd9ad8

I tried an online tool and it appears that the difference between the two is that the one the people I am working with are expecting a HEX type signature key.

Is there something I need to add to my PHP in order to output the HEX type?


Solution

  • You'll need to convert the hexadecimal string to binary data before passing it into hash_hmac:

    var_dump(hash_hmac("sha1", "office:fred", pack("H*", "AA381AC5E4298C23B3B3333333333333333333")));
    

    Outputs 46abe81345b1da2f1a330bba3d6254e110cd9ad8 as expected.