Reputation: 30158
I'm trying to port a PHP example of an API integration to Javascript / JQuery. In PHP, an encrypted string is created using the following code:
$sig = base64_encode(hash_hmac('sha256', $sign, $this->secretAccessKey, true)
whose functions are documented here:
http://php.net/manual/en/function.hash-hmac.php
http://us.php.net/base64_encode
In Javascript, I'm using JQuery's crypto to do the HMAC piece:
http://code.google.com/p/crypto-js/#HMAC-SHA256
and I'm trying to figure out if I also need to do a base64 encode, as it seems it is already in base64. This is the code I'm currently running:
var sigHash = Crypto.HMAC(Crypto.SHA256, sign, accessKey);
Is this correct? How would I create a javascript / jquery equivalent of the above PHP function?
Upvotes: 0
Views: 6928
Reputation: 14477
HMAC is a standard. So is SHA-256. So their outputs, regardless of which implementation, has to be the same.
There could only be differences in the Base64 encoding. Normally, the non-alphanumeric characters are +
and /
, but you cannot count on that. I've checked, and both implementations use the same non-alphanumeric characters.
However, you should still "manually" check a few thousand strings. The implementation in PHP is well tested. But I do not know if the same is true for the implementation in jQuery...
The syntax for Base64 encoded output is:
Crypto.util.bytesToBase64(
Crypto.HMAC(Crypto.SHA256, sign, accessKey, { asBytes: true })
);
Upvotes: 2
Reputation: 348972
If you ever need inspiration for a JS implementation of a PHP function, have a look at PHPJS.org. The JavaScript equivalent for base64_encode
can be found at: base64_encode.
Upvotes: 1