0

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?

2 Answers 2

2

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 })
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - I think what I need to know though, is it enough just to run the crypto function in javascript to get the equivalent to the PHP functions, or do I need to run the crypto function, and an addition base64_encode function
The standard output of the function is hexadecimal encoding, not Base64. For Base64 encoding, see updated answer.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.