0

for caching purpose, I want to generate a sha256 hash for various payloads. The hash should be safe enough, to ignore changes in the order of fields.

For form data, this would be fairly easy, e.g. this body foo=bar&test=data can be splitted by & and = sorted, joined and then hashed like this:

require 'digest'
data = "test=data&foo=bar"
joined_data = data.split("&").map {|pair| pair.split("=") }.sort { |a,b| a[0] <=> b[0] }.flatten.join
Digest::SHA256.hexdigest joined_data
# => "cf0bb2aa96a34e404a2901eec34214033dbf73f4242330f0e77c534bf38da585"

But for JSON data, this is much more difficult. First, the order of the keys doesn't matter for the content, but the order inside arrays does matter, keys and arrays can be nested and so on...

I could implement a JSON.parse(body), then convert the ruby hash to an array, sort the keys and do everything recursivly (also inside arrays) until we are finished.

1st question: Is there already a solution for hashing JSON data?

2nd question: Besides JSON, form data, plain strings and binary data, what other data structures should I consider, where the order is unimportant? XML? Anything else?

23tux
  • 14,104
  • 15
  • 88
  • 187

0 Answers0