Skip to content

Instantly share code, notes, and snippets.

@philipaconrad
Created April 14, 2015 04:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipaconrad/15c7d1dc086fe62a304e to your computer and use it in GitHub Desktop.
Save philipaconrad/15c7d1dc086fe62a304e to your computer and use it in GitHub Desktop.
Command line utility for checking hashes and checksums of files easily. [MIT License]
# sig.py -- Basic hash and checksum utility in Python.
# Copyright (c) Philip Conrad, 2015. All rights reserved.
# Released under the MIT License. (http://opensource.org/licenses/MIT)
import hashlib
import sys
import argparse
# Function for incrementally reading text from HUGE files.
def read_file(f, block_size=1024):
# f is an already open file.
while True:
piece = f.read(block_size)
if piece:
yield piece
else:
return
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate hashes for files.')
parser.add_argument('filenames', type=argparse.FileType('rb'), nargs='+',
help='filenames to compute hashes for.')
# Algorithms that are always available in hashlib:
# md5(), sha1(), sha224(), sha256(), sha384(), and sha512().
parser.add_argument("--md5", action="store_true",
help="use MD5 hash algorithm")
parser.add_argument("--sha1", action="store_true",
help="use SHA1 hash algorithm")
parser.add_argument("--sha224", action="store_true",
help="use SHA224 hash algorithm")
parser.add_argument("--sha256", action="store_true",
help="use SHA256 hash algorithm")
parser.add_argument("--sha384", action="store_true",
help="use SHA384 hash algorithm")
parser.add_argument("--sha512", action="store_true",
help="use SHA512 hash algorithm")
# If no args provided, print help and terminate.
if len(sys.argv[1:]) == 0:
parser.print_help()
# parser.print_usage() # for just the usage line
parser.exit()
args = parser.parse_args()
m = None
algo = ""
if args.md5:
m = hashlib.md5()
elif args.sha1:
m = hashlib.sha1()
elif args.sha224:
m = hashlib.sha224()
elif args.sha256:
m = hashlib.sha256()
elif args.sha384:
m = hashlib.sha384()
elif args.sha512:
m = hashlib.sha512()
else:
parser.print_help()
parser.exit()
# 'm' should always be initialized by this point.
for f in args.filenames:
h = m.copy() # Copy the current hash algorithm.
for chunk in read_file(f): # Get the plaintext to be hashed.
h.update(chunk) # Run text through the hash algorithm.
print f.name + " :: " + h.hexdigest() # Print out results.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment