Generate a consistent sha256 hash from an object in Node

Viewed 2600

I have an object that I'd like to hash with sha256 in Node. The contents of the object are simple Javascript types. For example's sake, let's say:

var payload = {
    "id": "3bab3f00-7d55-11e7-9b0a-4c32759242a5",
    "foo": "a message",
    "version": 7,
};

I create a hash like this:

const crypto = require('crypto');
var hash = crypto.createHash('sha256');
hash.update( ... ).digest('hex');

The question is, what to pass to update? The documentation for crypto says you can pass a <string> | <Buffer> | <TypedArray> | <DataView>, which seems to suggest an object is not a good thing to pass.

I can't use toString() because that prints "[object Object]". I could use JSON.stringify, however I have read elsewhere that the output from stringify is not guaranteed to be deterministic for the same input.

Are there any other options? I do not want to download a package from NPM.

1 Answers
Related