Learn MD5 File Hashing and API Integration

Introduction to MD5 File Hashing

MD5 is a widely used cryptographic hash function that produces a 128-bit hash value. It is commonly utilized for checking data integrity. In this tutorial, we will explore how to create an MD5 hash of a file and provide dozens of useful API examples along with code snippets.

MD5 File Hashing APIs

Below are some common functions for MD5 file hashing.

1. Generating MD5 Hash in Python


import hashlib

def md5_file(filename):
    hash_md5 = hashlib.md5()
    with open(filename, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

print(md5_file("example.txt"))

2. Generating MD5 Hash in Node.js


const crypto = require('crypto');
const fs = require('fs');

function md5File(filename) {
    return new Promise((resolve, reject) => {
        const hash = crypto.createHash('md5');
        const stream = fs.createReadStream(filename);
        stream.on('data', (data) => hash.update(data));
        stream.on('end', () => resolve(hash.digest('hex')));
        stream.on('error', (err) => reject(err));
    });
}

md5File('example.txt').then(console.log).catch(console.error);

3. Generating MD5 Hash in Java


import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class MD5Checksum {
    public static void main(String[] args) throws Exception {
        String filename = "example.txt";
        System.out.println(getMD5Checksum(filename));
    }

    public static String getMD5Checksum(String filename) throws Exception {
        byte[] buffer = new byte[1024];
        int bytesRead;
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream fis = new FileInputStream(filename)) {
            while ((bytesRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        byte[] hashBytes = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

Creating an App Using MD5 Hashing APIs

Now, let’s see how to create a simple file verification app that uses the MD5 hashing function.

File Verification App in Python


import hashlib

def md5_file(filename):
    hash_md5 = hashlib.md5()
    with open(filename, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def verify_file(filename, expected_hash):
    return md5_file(filename) == expected_hash

filename = "example.txt"
expected_hash = "5d41402abc4b2a76b9719d911017c592"
if verify_file(filename, expected_hash):
    print("File is valid")
else:
    print("File is corrupted or modified")

Hash: db72603ad186cb4abafe5ef448372feb3e5dba56304945997609d8c420d9da1a

Leave a Reply

Your email address will not be published. Required fields are marked *