Object Hash Generator

3.0.0 · active · verified Sun Apr 19

object-hash is a JavaScript library designed to generate consistent hashes from various JavaScript objects and primitive values in both Node.js and browser environments. It leverages Node.js's built-in `crypto` module for hashing algorithms like SHA1 (default), MD5, and others available via `crypto.getHashes()`, as well as supporting custom stream processing. The current stable version is 3.0.0. A key aspect of its API contract, established since version 1.1.8 (April 2017), is that any changes affecting the exact returned hash value are considered `semver-major`, ensuring predictability for users. It differentiates itself by offering extensive configuration options, including the ability to ignore values, sort arrays/objects/sets for order-independent hashing, and respect or ignore function properties, making it highly flexible for use cases like caching, deduplication, or content addressing where object state needs to be consistently fingerprinted. It is important to note that default algorithms like SHA-1 and MD5 are not considered cryptographically secure and should not be used for security-sensitive applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic object hashing, specifying a different algorithm and encoding, hashing only object keys, and ensuring order-independent hashing for objects and arrays.

const hash = require('object-hash');

// Basic hashing of an object
const objectHash = hash({ foo: 'bar', baz: [1, 2, { a: 3 }] });
console.log('Object Hash:', objectHash); // Example: '37a3c3d5e21d5a7b6c7a9f8d9b6e2d1f0a8c4b2e'

// Hashing with specific algorithm and encoding (e.g., SHA256)
const sha256Hash = hash({ data: 'sensitive info' }, { algorithm: 'sha256', encoding: 'base64' });
console.log('SHA256 Hash (Base64):', sha256Hash);

// Hashing an object, ignoring values (only keys contribute to hash)
const keysOnlyHash = hash({ name: 'Alice', age: 30 }, { excludeValues: true });
console.log('Keys-only Hash:', keysOnlyHash);

// Hashing with unordered objects and arrays for consistent results regardless of property/element order
const unorderedHash1 = hash({ x: 1, y: 2 }, { unorderedObjects: true, unorderedArrays: true });
const unorderedHash2 = hash({ y: 2, x: 1 }, { unorderedObjects: true, unorderedArrays: true });
console.log('Unordered Object Hash 1:', unorderedHash1);
console.log('Unordered Object Hash 2:', unorderedHash2);
console.log('Unordered hashes match:', unorderedHash1 === unorderedHash2);

view raw JSON →