简体   繁体   中英

Hash an array in Javascript and PHP

I'm trying to pass a message from a Javascript Client to a PHP webserver. To add a layer of security I would like to sign the data object with an hash.

/* Generate signature of the data with the password */
that.signEnvelope = function(data,password)
{
      return CryptoJS.SHA256(JSON.stringify(data) + password).toString();
};

This quickly falls apart on the server. The JSON.stringify function does not generate a 1:1 matching string to json_encode on the server making it impossible to verify the hash.

protected function verifySignature($remoteSignature,$data,$privateKey)
{
    /* Combine json & key samen , then sha256 */
    $localSignature = hash('sha256',json_encode($data) . $privateKey);
    return ($localSignature === $remoteSignature);
}

Is there another algorithm that I can implement in both PHP and Javascript that will generate a hashable string ?

Conclusion

Allowing json_encode accross platforms was not a smart thing todo. There is no standard implementation.

Instead I now only allow arrays with string key/value pairs which are much easier to concat and verify.

What you experiencing there is not limited to certain differing whitepace/linebreak-characters. It is also worth mentioning, that different charsets can lead to different output. A ISO8859-15 Euro-Sign is 1 byte long, a UTF8 Euro-Sign is 3 bytes long and there is always the chance to encode a Char with the \\u####-declaration. JSON-libs is not intended to produce comparable strings over different plattforms.

If you still want to utilize JSON, you have to either use libs, that behave identical on all input, or build your own. JSON is easy to generate by hand.

You could use the JS version of json_encode to get a 1:1 match:

http://phpjs.org/functions/json_encode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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