Skip to content

Instantly share code, notes, and snippets.

@airtower-luna
Created August 20, 2020 16:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airtower-luna/a5df5d6143c8e9ffe7eb5deb5797a0e0 to your computer and use it in GitHub Desktop.
Save airtower-luna/a5df5d6143c8e9ffe7eb5deb5797a0e0 to your computer and use it in GitHub Desktop.
Example of how to verify an SHA-256 checksum file using Python
#!/usr/bin/python3
# Example of how to verify an SHA-256 checksum file using Python.
# Usage: python sha256check.py 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 = fh.read(4096)
if len(data) == 0:
break
else:
h.update(data)
return expect == h.hexdigest()
with open(sys.argv[1]) as fh:
for line in fh:
m = r.match(line)
if m:
checksum = m.group(1)
filename = m.group(2)
if check(filename, checksum):
print(f'{filename}: OK')
else:
print(f'{filename}: BAD CHECKSUM')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment