DebugPointer
Published on

Create MD5 hash of a dict in JavaScript

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 backend using Nodejs, Expressjs or so, you can work with the native crypto module 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.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MD5</title>
  </head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/md5.js"></script>
    <script>
      const person = { name: "Vamana", age: 20 }
      const orderedPerson = Object.fromEntries(Object.entries(person).sort())
      let hash = CryptoJS.MD5(JSON.stringify(orderedPerson))
      console.log(hash)
    </script>
  </body>
</html>

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.