How to compute the hash of a JSON document?
You don’t need to serialize the document to a temporary buffer to compute its hash (e.g., CRC or MD5).
Instead, you can write a custom writer that will do that on the fly.
Here is a writer that uses the FastCRC library to compute the CRC32 of a JSON or MessagePack document:
#include <FastCRC.h> // https://github.com/FrankBoesing/FastCRC
class CrcWriter {
public:
CrcWriter() {
_hash = _hasher.crc32(NULL, 0);
}
size_t write(uint8_t c) {
_hash = _hasher.crc32_upd(&c, 1);
return 1;
}
size_t write(const uint8_t *buffer, size_t length) {
_hash = _hasher.crc32_upd(buffer, length);
return length;
}
uint32_t hash() const {
return _hash;
}
private:
FastCRC32 _hasher;
uint32_t _hash;
};
Use this class like so:
CrcWriter writer;
serializeJson(doc, writer);
Serial.println(writer.hash());