How to deterministically hash lua tables?

Hi,

I’m trying to generate a SHA-256 hash from a table (with any possible content), meaning that tables with identical content should always produce the same hash, regardless of key order.
Since Lua tables are unordered, I’m running into an issue where key iteration order changes the resulting hash.

My current approach is to JSON-encode the table and hash the resulting string:

function hash(data)
	local input = HttpService:JSONEncode(data)
	local hash = EncodingService:ComputeStringHash(input, Enum.HashAlgorithm.Sha256)
	return hash
end

However, JSONEncode() doesn’t guarantee dictionary keys to be ordered.

Is there any way without making my own canonizer?

Thanks.

You could load the keys into a separate array and then call table.sort() on it. The sorting should put the string keys in alphabetical order. then you could iterate through the array of keys and run your hashing algorithm that way (so the keys are always in a set order).

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.