Question

I've spent past 6 hours implementing message signing algorithm.. It does not work AT ALL:

This is PHP code to generate digest:

$payload = "thisisanapple";
$signature = hash_hmac("sha1", $payload, "thisisarandomkey");
$data = base64_encode($signature);
// YzExZWRmZDliMjQzNTZjNzhlNmE3ZTdmMDE3ODJjNmMxMmM4ZTllMQ==

This is JS running on the Node.js server doing the same thing:

var hmac = crypto.createHmac('sha1', "thisisarandomkey");
hmac.update("thisisanapple");
var signature = hmac.digest('base64');
// wR7f2bJDVseOan5/AXgsbBLI6eE=

I have no clue what is wrong here.. I have tries SHA256, but they still differ. I also used a private key generated with OpenSSL, both in plaintext and in base64, still same result (different keys).

Was it helpful?

Solution

hash_hmac has four parameters and the last one specifies the output and by default hash_hmac returns hex string, not the raw data. So base64_encode encodes hex string in the PHP code fragment.

This one will work well:

$payload = "thisisanapple";
$signature = hash_hmac("sha1", $payload, "thisisarandomkey", true);
$data = base64_encode($signature);
// wR7f2bJDVseOan5/AXgsbBLI6eE=

OTHER TIPS

If you want to duplicate the PHP behaviour in JS, here is the code:

hmac = crypto.createHmac('sha1', 'thisisarandomkey')
signature = hmac.update('thisisanapple')
data = new Buffer(hmac.digest('hex')).toString('base64')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top