The Simplest to Calculate Checksum

by:

Python

This tutorial shows the Simplest to Calculate Checksum. It shares a Python function that handles the MD5 and SHA256 hashing functions which can be used to check your file(s) integrity.

1. Checksum: MD5 and SHA256

First and foremost, the simple Python function below can be used to calculate the checksum for files using the MD5 and SHA26 hashing functions.

# !/usr/bin/env python3
# -*- coding: utf-8 -*-


import hashlib


def get_checksum(filename, hash_function):
    """Generate checksum for file baed on hash function (MD5 or SHA256).

    Args:
        filename (str): Path to file that will have the checksum generated.
        hash_function (str):  Hash function name - supports MD5 or SHA256

    Returns:
        str`: Checksum based on Hash function of choice.

    Raises:
        Exception: Invalid hash function is entered.

    """
    hash_function = hash_function.lower()

    with open(filename, "rb") as f:
        bytes = f.read()  # read file as bytes
        if hash_function == "md5":
            readable_hash = hashlib.md5(bytes).hexdigest()
        elif hash_function == "sha256":
            readable_hash = hashlib.sha256(bytes).hexdigest()
        else:
            Raise("{} is an invalid hash function. Please Enter MD5 or SHA256")

    return readable_hash

2. Test case

Moreover, I downloaded a random image online and computed the checksum for MD5 and SHA256 hashing functions using the Python function and to compare it to the one generated using Unix commands.

import os

photo = "g_circle-300x300.png"
md5_result = get_checksum(photo, "md5")
sha256_result = get_checksum(photo, "sha256")

os.system("md5 {}".format(photo))
print('Hash Function: MD5 - Filename: {}'.format(md5_result))

os.system("shasum -a 256 {}".format(photo))
print('Hash Function: SHA256 - Filename: {}'.format(sha256_result))

which prints as

MD5 (g_circle-300x300.png) = 0100c08784ed0f8defa8c9156b45a97e
Hash Function: MD5 - Filename: 0100c08784ed0f8defa8c9156b45a97e
132124053114b94b46e421dbc4587a15e6962d812389d1705c66d431f1944b9e  g_circle-300x300.png
Hash Function: SHA256 - Filename: 132124053114b94b46e421dbc4587a15e6962d812389d1705c66d431f1944b9e

Last but not least, in case you want to learn more about checksum, please check the Youtube video below:

More Resources

Here are three of my favorite Python Books in case you want to learn more about it.

Conclusion

In Summary, I hope this tutorial was useful for you. Hopefully, you learned how simple it is to check for file integrity for MD5 and SHA256.

Comment below for what kind of application you need to calculate the MD5 and SHA256 hashes.

Related Posts