简体   繁体   English

如何在javascript中的嵌套对象中对键的顺序进行排序?

[英]How can I sort the order of key in a nested object in javascript?

the problem is: I have a request with params like: 问题是:我有如下参数请求:

{ "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } }

I need to sign it with Hmac512 algorithm, so I'll need to stringify the object first. 我需要使用Hmac512算法对其进行签名,因此需要首先对对象进行字符串化。

But, my concern is, if the order of the key isn't preserved, the signature generated by server and the client could be different. 但是,我担心的是,如果不保留密钥的顺序,则服务器和客户端生成的签名可能会不同。

to handle that, my idea is simply to order the keys of the object (including the keys nested inside that object). 为了解决这个问题,我的想法只是简单地对对象的键进行排序(包括嵌套在该对象内部的键)。

how can I achieve this? 我该如何实现?

As stated in the OP, the input to the HMAC process must be deterministic. 如OP中所述,HMAC流程的输入必须是确定性的。

But Javascript object elements' order cannot be set, no matter how much we'd like them to be settable. 但是,无论我们希望设置多少Javascript对象元素的顺序,都无法设置。 (I see this question re-occur every so often.) (我经常看到这个问题。)

Answer is to sort the the stringified string itself. 答案是对字符串本身进行排序。

See json-stable-stringify for a solution. 有关解决方案,请参见json-stable-stringify

Then feed the resulting string into the HMAC method. 然后将结果字符串输入HMAC方法。 No need to base64 encode it. 无需对它进行base64编码。

You need to ensure that the message is the same in both sides, but you should not need to modify or adapt the message at all 您需要确保双方的信息都是相同的,但是您根本不需要修改或改写该信息。

Basically apply this algorithm 基本上应用这个算法

 base64(sign(utf8(json message)))

Client side 客户端

  1. Stringify: Convert the javascript object to string Stringify:将javascript对象转换为字符串

  2. UTF-8: Ensure you are using a known and fixed encoding like utf UTF-8:确保您使用的是已知且固定的编码,例如utf

  3. Sign: Calculate HMAC over the resulting message 签名:根据结果消息计算HMAC

  4. base64: Convert the binary signature to base64 base64:将二进制签名转换为base64

Send to client the json message and the signature 向客户端发送json消息和签名

Server side 服务器端

Get the raw message from client and apply steps 2-4. 从客户端获取原始消息并应用步骤2-4。 Check if the signatures are equal 检查签名是否相等

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

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