Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reliably hash JavaScript objects?
    primarykey
    data
    text
    <p>Is there a reliable way to JSON.stringify a JavaScript object that guarantees that the ceated JSON string is the same across all browsers, node.js and so on, given that the Javascript object is the same?</p> <p>I want to hash JS objects like</p> <pre><code>{ signed_data: object_to_sign, signature: md5(JSON.stringify(object_to_sign) + secret_code) } </code></pre> <p>and pass them around across web applications (e.g. Python and node.js) and the user so that the user can authenticate against one service and show the next service "signed data" for that one to check if the data is authentic.</p> <p>However, I came across the problem that JSON.stringify is not really unique across the implementations:</p> <ul> <li>In node.js / V8, JSON.stringify returns a JSON string without unnecessary whitespace, such as '{"user_id":3}.</li> <li>Python's simplejson.dumps leaves some whitespace, e.g. '{"user_id": 3}'</li> <li>Probably other stringify implementations might deal differently with whitespace, the order of attributes, or whatever.</li> </ul> <p>Is there a reliable cross-platform stringify method? Is there a "nomalised JSON"?</p> <p>Would you recommend other ways to hash objects like this?</p> <p><strong>UPDATE:</strong></p> <p>This is what I use as a workaround:</p> <pre><code>normalised_json_data = JSON.stringify(object_to_sign) { signed_data: normalised_json_data, signature: md5(normalised_json_data + secret_code) } </code></pre> <p>So in this approach, not the object itself, but its JSON representation (which is specific to the sigining platform) is signed. This works well because what I sign now is an unambiguous string and I can easily JSON.parse the data after I have checked the signature hash.</p> <p>The drawback here is that if I send the whole {signed_data, signature} object as JSON around as well, I have to call JSON.parse twice and it does not look as nice because the inner one gets escaped:</p> <pre><code>{"signature": "1c3763890298f5711c8b2ea4eb4c8833", "signed_data": "{\"user_id\":5}"} </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload