I need to exchange JSON objects between different platforms and implementations of the service and make its integrity verifiable through digital signatures. Thus, platform A will create such an object and create a digital signature. The specified signature is then included in the object and sent to platform B. JSON objects can contain arbitrary attributes and data.
eg. in PHP:
function signObject($jsonObjectToSign, $privateKey) { $jsonObjectToSign->signature = ""; $msgToSign = json_encode($jsonObjectToSign); openssl_sign($msgToSign, $jsonObjectToSign->signature, $privateKey, OPENSSL_SLGO_SHA1); return $jsonObjectToSign; }
The problem is that, for example, in Java there is no way to determine whether the attributes of the JSON object will be in the same order in which you added them (via JSONObject.put ()). So if i do
$json = json_encode('{"a":1, "b":2}');
in PHP, sign this object as described above, transfer it to a Java-based server, decode the json object, and then try to verify the signature, I would probably get a different order of object attributes.
So what I need is a reliable way to create a String from a JSONObject, regardless of the language or platform used.
The above example should always output {"a":1, "b":2} and NEVER {"b":2, "a":1} . Unfortunately, this is a common case, for example. in java.
Is there a โbest practiceโ for safely signing JSON objects?
But let me describe the problem differently:
Say I want to do this in Java (or any other language):
JSONObject j = new JSONObject(); j.put("a", 1); j.put("b", 2);
Now I need a serialization function that always displays the same string representation for this object, no matter how and with what language this object is created.