Create MD5 hash of a dict in JavaScript
As we've seen in earlier posts, you can create an MD5 hash of a string and generate a hash in string type.
In JavaScipt, an Object is a data structure that stores key-value pairs. The keys are used to access the values.
Example -
const person = { name: "Vamana", age: 20 };
In case you are working on the frontend (JavaScript, React, Vue or so), you can work with the CryptoJS library to create MD5 hash of an Object.
But, what if you had to create an md5 hash of the person
object above? We can do it by first converting the Object
type to string format. Note that, a object doesn't maintain the order of keys (key:values), so the value can change randomly when you try to use it as a complete object. For this reason, we will sort the keys and then convert it to a string, to make sure that the order of keys is consistent always. We do this by sorting the person
object to orderedPerson
object and then performing a JSON.stringify()
to stringify the JSON object as shown in the example below.
Here is an example with complete code of the above mentioned implementation.
import { createHash } from "crypto";
const person = { name: "Vamana", age: 20 };
const orderedPerson = Object.fromEntries(Object.entries(person).sort());
const hash = createHash("md5")
.update(JSON.stringify(orderedPerson))
.digest("hex");
console.log(hash);
The output of the above JavaScript code will return a MD5 hash of the stringified version of the object-
267754bb3882c89041b0db2622f5b241
I'm glad that you found this article to create MD5 hash of an object in JavaScript useful. Happy Coding.