DebugPointer
Published on

Create MD5 Hash in Node.js

Create MD5 Hash in Node.js

MD5 is (atleast when it was created) a standardized 1-way function that takes in data input of any form and maps it to a fixed-size output string, irrespective of the size of the input string.

Though it is used as a cryptographic hash function, it has been found to suffer from a lot of vulnerabilities.

The hash function generates the same output hash for the same input string. This means that, you can use this string to validate files or text or anything when you pass it across the network or even otherwise. MD5 can act as a Stamp or for checking if the data is valid or not.

For example -

Input StringOutput Hash
hi49f68a5c8493ec2c0bf489821c21fc3b
debugpointerd16220bc73b8c7176a3971c7f73ac8aa
computer science is amazing! I love it.f3c5a497380310d828cdfc1737e8e2a3

If you want to generate md5 checksum in JavaScript i.e., client side (browser), please follow this article - Create MD5 Hash in JavaScript

Node.js crypto module provides cryptographic functions to help you secure code and data in Node.js. It includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions.

crypto is built into Node.js, so there is not configuration or custom implementation needed.

For creating MD5 hash in nodejs script/code, we shall use the default crypto module that comes packaged with nodejs.

Creating MD5 Hash of a String

You can either require the crypto module-

const crypto = require('crypto')

or also use the modern import to import the crypto module-

import { createHash } from 'crypto'
import { createHash } from 'crypto'
const yourString = "This works"
const hash = createHash("md5").update(yourString).digest("hex")
console.log(hash)

The output of the above script will be an MD5 hash when you run the command node index.js in your shell-

55b54ce1630aefc1fcc907ed53bc1b09

If you looking to create an MD5 hash of a file, please follow the article where we discuss as to how to read a file buffer and create the hash.

NOTE : Please do not use this to hash passwords and store it in your databases, prefer SHA-256 or SHA-512 or other superior cryptographic hash functions for the same.

It's as simple as that! You do not need any fancy npm library for creating an MD5 hash in Node.js.

Related articles

Let me summarize creating a hash in JavaScript and Nodejs, so that it becomes easy for you to refer-

I'm glad that you found the content useful. Happy Coding.