PHP / Javascript / JQuery - base64 sha256 encoding

你说的曾经没有我的故事 提交于 2019-12-01 12:40:17

问题


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?


回答1:


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 })
);



回答2:


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.



来源:https://stackoverflow.com/questions/7909288/php-javascript-jquery-base64-sha256-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!