Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of how to verify an SHA-256 checksum file using Python
# Example of how to verify an SHA-256 checksum file using Python.
# Usage: python sha256sum.txt
import hashlib
import re
import sys
# This regular expression matches a line containing a hexadecimal
# hash, spaces, and a filename. Parentheses create capturing groups.
r = re.compile(r'(^[0-9A-Fa-f]+)\s+(\S.*)$')
def check(filename, expect):
"""Check if the file with the name "filename" matches the SHA-256 sum
in "expect"."""
h = hashlib.sha256()
# This will raise an exception if the file doesn't exist. Catching
# and handling it is left as an exercise for the reader.
with open(filename, 'rb') as fh:
# Read and hash the file in 4K chunks. Reading the whole
# file at once might consume a lot of memory if it is
# large.
while True:
data =
if len(data) == 0:
return expect == h.hexdigest()
with open(sys.argv[1]) as fh:
for line in fh:
m = r.match(line)
if m:
checksum =
filename =
if check(filename, checksum):
print(f'{filename}: OK')
print(f'{filename}: BAD CHECKSUM')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.