简体   繁体   English

PHP / Javascript / JQuery-base64 sha256编码

[英]PHP / Javascript / JQuery - base64 sha256 encoding

I'm trying to port a PHP example of an API integration to Javascript / JQuery. 我正在尝试将API集成的PHP示例移植到Javascript / JQuery。 In PHP, an encrypted string is created using the following code: 在PHP中,使用以下代码创建加密的字符串:

$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://php.net/manual/zh/function.hash-hmac.php

http://us.php.net/base64_encode http://us.php.net/base64_encode

In Javascript, I'm using JQuery's crypto to do the HMAC piece: 在Javascript中,我使用JQuery的加密算法来完成HMAC部分:

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. 并且我试图找出是否还需要进行base64编码,因为它似乎已经在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? 如何创建与上述PHP函数等效的javascript / jquery?

HMAC is a standard. HMAC是一个标准。 So is SHA-256. SHA-256也是如此。 So their outputs, regardless of which implementation, has to be the same. 因此,无论采用哪种实现,它们的输出都必须相同。

There could only be differences in the Base64 encoding. Base64编码中可能仅存在差异。 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. PHP中的实现已经过测试。 But I do not know if the same is true for the implementation in jQuery... 但是我不知道jQuery的实现是否也是如此...

The syntax for Base64 encoded output is: Base64编码输出的语法为:

Crypto.util.bytesToBase64(
    Crypto.HMAC(Crypto.SHA256, sign, accessKey, { asBytes: true })
);

If you ever need inspiration for a JS implementation of a PHP function, have a look at PHPJS.org. 如果您需要灵感来实现PHP函数的JS实现,请访问PHPJS.org。 The JavaScript equivalent for base64_encode can be found at: base64_encode . 可在base64_encode中找到与base64_encode等效的JavaScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM