DebugPointer
Published on

Create SHA3-256 Hash of a file in Python

Create SHA3-256 Hash of a file in Python

Encryption and hashing have served as the foundation for new security modules, among other network security developments. One of the most used hash algorithms is the Secure Hash Algorithm(SHA) with a digest size of 256 bits, or SHA 256. Although there are numerous variations, SHA 256 has been the most often used in practical applications.

SHA-3 (Secure Hash Algorithm 3) is the latest member of the Secure Hash Algorithm family of standards. Although part of the same series of standards, SHA-3 is internally different from the MD5-like structure of SHA-1 and SHA-2. SHA-3 instances are drop-in replacements for SHA-2, intended to have identical security properties. The SHA-3 family consists of six hash functions with digests (hash values) that are 128, 224, 256, 384 or 512 bits: SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256.

The SHA-3 or Keccak algorithm is one of the most secure and efficient hashing algorithms and some claim that it won’t be cracked in the next 20 - 30 years. Developments in the quantum computing world might decrease that time frame but it is still one of the best hashing algorithm we have got right now.

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. SHA3-256 can act as a stamp or for checking if the data is valid or not.

The 256 in the name SHA3-256 refers to the final hash digest value, meaning that regardless of the amount of plaintext or cleartext, the hash value will always be 256 bits.

For example -

Input StringOutput Hash
hib39c14c8da3b23811f6415b7e0b33526d7e07a46f2cf0484179435767e4a8804
debugpointer5bd28b8b5e1c0c8355362e581d0c478842ee79840adfe0307139179a2ff5d5de
computer science is amazing! I love it.9d9c88852fed897f23a898f0994b325cff9c70b629c96eff3739c4ffb1459edf

Check this out - If you are looking for SHA3-256 hash of a String.

Create SHA3-256 hash of a file in Python

SHA3-256 hash can be created using the python's default module hashlib.

Incorrect Way to create SHA3-256 Hash of a file in Python

But, you have to note that you cannot create a hash of a file by just specifying the name of the file like this-

# this is NOT correct
import hashlib
print(hashlib.sha3_256("filename.jpg".encode('UTF-8')).hexdigest())

Output of the above code-

5a9bca39c0583dcdabca4943cce8ffcbff51e699c73f8210a4a88ea6c9191a51

The above value is NOT the SHA3-256 hash of the file. But, it is the SHA3-256 hash of the string filename.jpg itself.

Correct Way to create SHA3-256 Hash of a file in Python

You have to read the contents of the file to create SHA3-256 hash of the file itself. It's simple, we can just read the contents of the file and create the hash.

The process of creating an SHA3-256 hash in python is very simple. First import hashlib, then encode your string that you want to hash i.e., converts the string into the byte equivalent using encode(), then pass it through the hashlib.sha3_256() function. We print the hexdigest value of the hash m, which is the hexadecimal equivalent encoded string.

import hashlib

file_name = 'filename.jpg'

with open(file_name) as f:
    data = f.read()
    sha256hash = hashlib.sha3_256(data).hexdigest()

SHA3-256 Hash of Large Files in Python

In the above code, there is one problem. If the file is a 10 Gb file, let's say a large log file or a dump of traffic or a Game like FIFA or others. If you want to compute SHA3-256 hash of it, it would probably chew up your memory.

Here is a memory optimised way of computing SHA3-256 hash, where we read chunks of 4096 bytes (can be customised as per your requirement, size of your system, size of your file etc.,). So, in this process we sequentially process the chunks and update the hash. So, in this process, let's say there are 1000 such chunks of the file, the hash_sha3_256 is updated 1000 times.

At the end we return the hexdigest value of the hash m, which is the hexadecimal equivalent encoded string.

import hashlib

# A utility function that can be used in your code
def compute_sha256(file_name):
    hash_sha3_256 = hashlib.sha3_256()
    with open(file_name, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_sha3_256.update(chunk)
    return hash_sha3_256.hexdigest()

Compare and Verify SHA3-256 hash of a file using python

You need to verify the SHA3-256 hash at the server or at some other point or logic in your code.

To verify the SHA3-256 hash you will have to create the SHA3-256 hash of the original file again.

Then compare the original SHA3-256 value that the source has generated and SHA3-256 that you generate.

import hashlib

file_name = 'filename.jpg'

original_sha256 = '5a9bca39c0583dcdabca4943cce8ffcbff51e699c73f8210a4a88ea6c9191a51'

with open(file_name) as f:
    data = f.read()
    sha256_returned = hashlib.sha3_256(data).hexdigest()

if original_sha256 == sha256_returned:
    print "SHA3-256 verified."
else:
    print "SHA3-256 verification failed."

A more complex hash can be created in SHA 3 family using the SHA3-512 algorithm in python for a file.

The process of SHA3-256 creation and verification is easy as we discussed above. Happy Coding!

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