如何可靠地哈希JavaScript对象? [英] How to reliably hash JavaScript objects?
问题描述
是否有一种可靠的方法来处理JSON.stringify一个JavaScript对象,以确保在所有浏览器,node.js等等中,cendant JSON字符串是相同的,因为Javascript对象是相同的?
b$ b
我想对像JS这样的对象进行哈希:
$ $ $ $ $ $ b $ signed_data:object_to_sign,
签名:md5(JSON.stringify(object_to_sign)+ secret_code)
}
并通过Web应用程序(例如Python和node.js)和用户传递它们,以便用户可以针对一个服务进行身份验证,并显示该服务的下一个服务签名数据以检查数据是否可信。
然而,我发现JSON.stringify在实现中并不是唯一的: 是否有可靠的跨平台串化方法?是否有一个nomalised JSON? 您会推荐其他方法来散列这样的对象吗? strong>更新: 这是我用作解决方法的一个方法: 所以在这种方法中,不是对象本身,而是它的JSON表示(专用于sigining平台)被签名。这很好,因为我现在签名的是一个明确的字符串,我可以轻松地JSON.parse数据后,我检查签名散列。 这里的缺点是,如果我将整个{signed_data,signature}对象作为JSON发送,我必须调用JSON.parse两次,它看起来并不好,因为内部的一个会被转义: 您需要跨多种语言实现相同的内容......您几乎肯定不幸运。您有两种选择: 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? I want to hash JS objects like 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. However, I came across the problem that JSON.stringify is not really unique across the implementations: Is there a reliable cross-platform stringify method? Is there a "nomalised JSON"? Would you recommend other ways to hash objects like this? UPDATE: This is what I use as a workaround: 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. 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:
You're asking for an implementation of something across multiple languages to be the same... you're almost certainly out of luck. You have two options: 这篇关于如何可靠地哈希JavaScript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
normalised_json_data = JSON.stringify(object_to_sign)
{
signed_data:normalised_json_data,
签名:md5(normalised_json_data + secret_code)
}
{signature:1c3763890298f5711c8b2ea4eb4c8833,signed_data:{\user_id \:5}}
{
signed_data: object_to_sign,
signature: md5(JSON.stringify(object_to_sign) + secret_code)
}
normalised_json_data = JSON.stringify(object_to_sign)
{
signed_data: normalised_json_data,
signature: md5(normalised_json_data + secret_code)
}
{"signature": "1c3763890298f5711c8b2ea4eb4c8833", "signed_data": "{\"user_id\":5}"}