CodeWars Challenge Password Hashes, Generating a MD5 hash in Node.JS

Well... what the heck?

Posted by Eralp on May 15, 2019

I get weekly CodeWars challenges in my email. This week I've got Password Hashes challenge that require me to do some magic that I am not aware of and no clue where to start?

Password Hashes challenge:

When you sign up for an account somewhere, some websites do not actually store your password in their databases. Instead, they will transform your password into something else using a cryptographic hashing algorithm.

After the password is transformed, it is then called a password hash. Whenever you try to login, the website will transform the password you tried using the same hashing algorithm and simply see if the password hashes are the same.

Create the function that converts a given string into an md5 hash. The return value should be encoded in hexadecimal.

You will need to use the NodeJS Crypto Module or libcrypto for the C and NASM versions.

Code Examples

passHash('password') //--> '5f4dcc3b5aa765d61d8327deb882cf99' passHash('abc123') //--> 'e99a18c428cb38d5f260853678922e03'

Lucky me that challenge's owner put a link to Node.js documentation NodeJs Crypto Module.

I've followed the URL and start reading docs, scrolled down to crypto.createHash(algorithm[, options]) then I found the following example.

Node.Js Documentation Example:

Generating the sha256 sum of a file
            
              const filename = process.argv[2];
              const crypto = require('crypto');
              const fs = require('fs');

              const hash = crypto.createHash('sha256');

              const input = fs.createReadStream(filename);
              input.on('readable', () => {
                // Only one element is going to be produced by the
                // hash stream.
                const data = input.read();
                if (data)
                  hash.update(data);
                else {
                  console.log(`${hash.digest('hex')} ${filename}`);
                }
              });
            
          

Where do we go from here?

  • I need to import module crypto
  • This module offers a way of an encapsulating credentials.
  • I than create md5 hash crypto.createHash('md5')
  • Module uses createHash() function which returns an instance of the hash object.
  • I also need to get the string and update update('password')
  • Hash object contains update() function to update the hash contents with the given data.
  • Finally I need to calculate passed data digest("hex")
  • The digest() function calculates the digest of all the passed data to be hashed.

Well that is it! I submit it and the code past all of the tests.

References by, Node.Js Crypto, Authentication using Node.Js.