Contents Overview
- What is MD5 File Hashing?
- Prerequisites For Generating an MD5 File Hash in JavaScript
- How to Generate an MD5 File Hash in JavaScript?
- Utilized Common Methods for Generating an MD5 File Hash in Node.js
- Example 1: Generating an MD5 File Hash in JavaScript
- Example 2: Generating an MD5 File Hash and Reading the File in JavaScript
- Alternate Approach 1: Generating MD5 Hash of a String in JavaScript
- Alternate Approach 2: Generating MD5 Hash of a Password in JavaScript
- Conclusion
What is MD5 File Hashing?
“MD5” is a one-way function that takes the data of any type as its input and maps it to a fixed-size output string, regardless of the given string’s size. The hash function creates the same/identical output hash for the provided string.
It is such that this string can be utilized to validate files or text upon passing across the network and MD5 verifies if the data is valid or not. Below is the demonstration:
Input Value | Returned Hash Value |
JavaScript | 686155af75a60a0f6e9d80c1f7edd3e9 |
Liam*88 | c9c77fd293a9bb6d172e36a4a04053ea |
Prerequisites For Generating an MD5 File Hash in JavaScript
The following are the prerequisites to be considered before generating an MD5 file hash:
Step 1: Setup the Project
First of all, initialize the project with the default values(via the “-y” flag) using the following cmdlet:
Bonus Tip: Create a “template.cjs” file instead of the “template.js” file to avoid the “module” type errors.
Step 2: Create a Text File
Create the text file “textfile.txt” to generate the MD5 hash value from the file content. Following is the file content to be evaluated:
Also, note that the “crypto” module will be required. Since it is a built-in module of Node.js, therefore, there is no need to install or configure it. Below is the demonstration:
Here, it is evident that there is no need to install this module separately.
How to Generate an MD5 File Hash in Node.js?
An MD5 hash of a file can be generated with the help of the “crypto” module and its methods such as “createHash()” and “digest()”. This module provides the cryptographic methods to make the data secure in Node.js.
Utilized Common Methods for Generating an MD5 File Hash in Node.js
Following are the methods commonly used to generate an md5 hash of the file:
readFileSync(): This method is used to read the files in a synchronous manner.
Syntax
In the given syntax:
- “pt” refers to the text file’s relative path.
- “opt” is an optional parameter that comprises the encoding and flag.
Return Value
It fetches the file’s content.
createHash(): This method creates a hash object to create the hash digests.
Syntax
In this syntax:
- “alg” indicates the dependency on accessible algorithms favored by the OpenSSL version.
- “opt” is an optional parameter that controls the stream behavior.
Return Value
It retrieves the Hash object.
hash.digest(): This method creates the digest’s data passed when creating a hash.
Syntax
Here, “enc” indicates the encoding type which can be “hex” or “base64”.
Return Value
It retrieves the string of the passed encoding.
Example 1: Generating an MD5 File Hash in Node.js
This example generates an md5 hash of the file content using the “crypto” and “fs” modules:
const get2 = require("fs");
const readmd5 = get2.readFileSync("textfile.txt");
const out = get1.createHash("md5").update(readmd5).digest("hex");
console.log("MD5 Hash of a File -> "+out);
The code explanation is as follows:
- First, import the “crypto” and “fs” modules to generate an md5 hash and work with files, respectively.
- Now, apply the “readFileSync()” method to read the specified file synchronously.
- After that, apply the “createHash()” method to create an md5 hash object referring to the file.
- The specified “hex” value as the “digest()” method’s parameter refers to the encoding type.
- Lastly, retrieve the md5 hash of the corresponding file.
Output
Execute the following cmdlet to generate an md5 file hash:
This outcome implies that the md5 hash of the target file is returned appropriately.
Example 2: Generating an MD5 File Hash and Reading the File in Node.js
In this demonstration, the md5 hash of a file can be fetched along with reading the file content:
var include2 = require('crypto');
var getHash = ( content ) => {
var genHash = include2.createHash('md5');
data = genHash.update(content, 'utf-8');
out= data.digest('hex');
return out;
}
var readFile = include1.createReadStream('textfile.txt');
var cont = ''
readFile.on('data', function(chunk) {
cont += chunk;
});
readFile.on('error', function(err){
console.log(err);
});
readFile.on('end',function(){
var content = getHash(cont) ;
console.log('File Content -> \n' + cont);
console.log('MD5 Hash of a File -> ' + content);
});
According to this block of code, perform the below-given steps:
- Likewise, include the discussed modules.
- Now, pass the data to be hashed by creating an md5 hash object and specifying the “hex” format.
- After that, create a read stream to read the specified file’s content.
- Moving ahead, read the file’s content and cope with the faced errors, if any.
- Finally, invoke the “getHash()” method to compute the md5 hash of the file content.
Output
Run the below code to retrieve the md5 hash of the file’s content:
From this outcome, it can be implied that the file’s content along with the md5 hash of the file is displayed appropriately.
Alternate Approach 1: Generating MD5 Hash of a String in Node.js
The following code demonstration generates an md5 hash of a string value:
var include = require('crypto');
var makeHash = include.createHash('md5').update(string).digest('hex');
console.log("MD5 Hash of a String -> "+makeHash);
In this code:
- Initialize the string against which the md5 hash value is to be retrieved and include the “crypto” module.
- After that, likewise, apply the “createHash()” and “digest()” methods to create a hash object and retrieve the string with respect to the passed encoding type i.e., “hex”.
- Lastly, return the md5 hash of the defined string.
Output
Alternate Approach 2: Generating MD5 Hash of a Password in Node.js
In this example, the MD5 hash of a password can be fetched instead:
var include = require('crypto');
var makeHash = include.createHash('md5').update(string).digest('hex');
console.log("MD5 Hash of a Password -> "+makeHash);
Here, specify the password and repeat the discussed steps for including the “crypto” module and applying the combined “update()” and “digest()” methods to generate an md5 hash of the password.
Output
Running the following cmdlet generates the md5 hash of the password:
Conclusion
The MD5 hash of a file can be generated by installing and importing the “crypto” module and making use of its methods like “createHash()” and “digest()” etc. Moreover, the md5 hash of a defined string or a password can also be generated. This basically secures the data by encrypting it based on the passed encoding format.