How to Calculate SHA256 Hash of a File in Python
SHA256 is a secure hash algorithm which creates a fixed length one way string from any input data. The algorithm is designed in such a way that two different input will practically never lead to the same hash value. This property can be used to verify the integrity of the data. If data and hash is obtained using different methods, we can verify the integrity of the data by computing the hash again and comparing it with the received hash.
SHA 256 hashing algorithm is widely used in security applications and protocols. The following python program computes the SHA256 hash value of a file. Note that the computed hash is converted to a readable hexadecimal string.
# Python program to find SHA256 hexadecimal hash string of a file import hashlib filename = input("Enter the input file name: ") with open(filename,"rb") as f: bytes = f.read() # read entire file as bytes readable_hash = hashlib.sha256(bytes).hexdigest(); print(readable_hash)
The above program may fail for large input files since we read the entire string to compute the hash. The following python program is an improved version capable of handling large files,
# Python program to find SHA256 hash string of a file import hashlib filename = input("Enter the input file name: ") sha256_hash = hashlib.sha256() with open(filename,"rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096),b""): sha256_hash.update(byte_block) print(sha256_hash.hexdigest())
Here is a sample output from the above program,
5f22669f6f0ea1cc7e5af7c59712115bcf312e1ceaf7b2b005af259b610cf2da