Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

HMAC SHA256 hex digest in javascript

I'm trying to write a javascript lib to push events to Pusher.

In the environment I'm using I can't use nodejs, so no require('crypto') ... or at least I do not know of a way of using it outside node.

I'm following the example guide here: http://pusher.com/docs/rest_api; I'm stuck in the part where it says I should generate the HMAC SHA256 hex digest.

I am using this library http://code.google.com/p/crypto-js/#HMAC

So, following the instructions on Pusher i wrote

CryptoJS.HmacSHA256(
  'POST\n/apps/3/channels/project-3/events\nauth_key=278d425bdf160c739803&auth_timestamp=1272044395&auth_version=1.0&body_md5=7b3d404f5cde4a0b9b8fb4789a0098cb&name=foo',
  '7ad3773142a6692b25b8'
);

But that's giving me 20b132baa2aaf44ea1fab814f0788aaa44eed23a2d252c72e4dc2aaea0d6ac24 instead of b3152b2bb5a5b0bae66435a498797aa763e9b74f86cc97c9175424f8308b2f80.

What is bothering me is that I didn't do the "hex digest" part, so maybe that's what I'm missing, but I couldn't find a suitable lib to do this in javascript. Do you spot any errors in what I did? Do you have a library to suggest?

Thanks in advance for any help.

Upvotes: 3

Views: 11387

Answers (1)

dahveed707
dahveed707

Reputation: 924

I was struggling with doing the exact same thing. Pusher's documentation should really be clearer about this issue. It turns out it's not the encyption methods. It's the order that you list your parameters. The body of your message has to be exactly formatted like this:

{"data":"{\\"message\\":\\"hello world\\"}","name":"my_event","channel":"test_channel"}

Data has to be first, then message, followed by name and then finally the channel name.

Then when you create your auth signature you have to list your parameters as so:

POST\n/apps/3/events\nauth_key=278d425bdf160c739803&auth_timestamp=1353088179&auth_version=1.0&body_md5=ec365a775a4cd0599faeb73354201b6f

So auth key is first, then the timestamp, followed by the auth version and finally the body md5.

I got it to work once I followed this exact pattern. Hopefully this helps!

Upvotes: 2

Related Questions