1

I have some PHP code that produces a hmac as follows:

<?php
$secret = "7pgj8Dm6";
$message = "Test\0Message";
echo base64_encode(hash_hmac('sha512', $message, base64_decode($secret), true))."\n";
echo "69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW/1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO mQxlsWNPrw==\n";
?>

When I try to produce similar code in node.js, I get a different base64 encoded result than I'd like to have, and I can't figure out why.

var hmac = function(msg, secret){
  var s = (new Buffer(secret, 'base64')).toString('utf8');
  var hmac = require('crypto').createHmac('sha512',s);
  hmac.update(msg);
  return hmac.digest('base64');
};

var secret = "7pgj8Dm6";
var message = "Test\0Message";
var wanted = "69H45OZkKcmR9LOszbajUUPGkGT8IqasGPAWqW/1stGC2Mex2qhIB6aDbuoy7eGfMsaZiU8Y0lO3mQxlsWNPrw==";
var got = hmac(message, secret);
if(wanted === got){
  console.log('All is fine.');
}else{
  console.log('Hash is wrong :(');
}
console.log('wanted:\t'+wanted);
console.log('got:\t'+got);

My motivation for this is the anxpro api, with which I'd like to play a bit.

Jakob Runge
  • 2,229
  • 6
  • 36
  • 42
  • You can use the node Crypto API. See http://stackoverflow.com/questions/7480158/how-do-i-use-node-js-crypto-to-create-a-hmac-sha1-hash – christophetd May 28 '15 at 14:33
  • I totally misread your post, sorry. :/ You can remove your comment, I will remove mine to keep your post clean. – christophetd May 28 '15 at 14:45

1 Answers1

1

Ok, I figured it out. The problem was that I was calling toString on the Buffer created in the hmac function. When I remove that, everything works fine.

var hmac = function(msg, secret){
  var s = new Buffer(secret, 'base64');
  var hmac = require('crypto').createHmac('sha512',s);
  hmac.update(msg);
  return hmac.digest('base64');
};
Jakob Runge
  • 2,229
  • 6
  • 36
  • 42