user2577707
user2577707

Reputation: 21

HMAC-MD5 signature - translate key from hex to byte format php

I need to digitally sign some post data using HMAC-MD5 algo.

I have the key and a sample string (to which I know what the hex sign should be.

My problem is when I use the hash_hmac php function the key it generates is different to what it should be.

The instructions are:

  1. translate HMAC key from hex to byte format - not sure how to do that

  2. sign the string using HMAC-MD5 procedure based on merchant’s HMAC key - this bit is fine

  3. translate signature from byte to hex format and associate it as value with parameter sign - not sure what to do here either

I've tried using this for step 1) $key2 = pack("H*" , $key) and this for step 2) bin2hex ( $sign ) which don't work as hoped.

The only online HMAC-MD5 generator that I've found that produced the correct sign is here: http://membres.multimania.fr/brudav/hash.php when 'hexa' is selected. I obviously don't know how this works it out though.

Can anyone offer me any advise?

Upvotes: 2

Views: 2095

Answers (1)

PleaseStand
PleaseStand

Reputation: 32082

$hmac = hash_hmac('md5', $data, hex2bin($key));

should give the same answer as the online calculator.

  • hex2bin converts the key from hex format to binary format (step 1), which hash_hmac expects. What you had tried with pack should also work for this purpose.
  • hash_hmac, with the default $raw_output = false, will produce a hex output (steps 2 and 3 combined).

Upvotes: 2

Related Questions