Any thoughts on my code? It's a simple hashing code that runs from the command line.
There just appears to be a lot of condition if
/ elif
entries in both of the main functions (hashingmethod
and hashcalculator
).
# hashcalculator.py
import sys
import hashlib
args = len(sys.argv)
def inputVerification():
if sys.argv[1] == "--help":
scriptHelp()
elif args < 5:
print "You have failed to execute the command correctly"
print "Please type 'hashcalculator --help' for more information"
else:
filename = sys.argv[2]
hashingMethod(filename)
def scriptHelp():
print "\n"
print "----------------------------------------"
print "\tWelcome to Hash Calculator"
print "----------------------------------------"
print "\n"
print "--help"
print "\n"
print "In order to calculate the hash value of a file, your command line syntax"
print "must be written as below:-"
print "\n"
print "\thashcalculator -f [file] -h [hash method]"
print "\teg. hashcalculator -f notepad.exe -h SHA1"
print "\n"
print "The recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512"
def hashingMethod(filename):
hashmethod = sys.argv[4].upper()
if hashmethod == "MD5":
hashCalculator(filename, "md5")
elif hashmethod == "SHA1":
hashCalculator(filename, "sha1")
elif hashmethod == "SHA224":
hashCalculator(filename, "sha224")
elif hashmethod == "SHA256":
hashCalculator(filename, "sha256")
elif hashmethod == "SHA384":
hashCalculator(filename, "sha384")
elif hashmethod == "SHA512":
hashCalculator(filename, "sha512")
else:
print "You have not entered a valid hashing method"
print "Please review the help document"
scriptHelp()
def hashCalculator(filename, hashmethod):
with open(filename, 'rb') as f:
if hashmethod == "md5":
m = hashlib.md5()
elif hashmethod == "sha1":
m = hashlib.sha1()
elif hashmethod == "sha224":
m = hashlib.sha224()
elif hashmethod == "sha256":
m = hashlib.sha256()
elif hashmethod == "sha384":
m = hashlib.sha384()
elif hashmethod == "sha512":
m = hashlib.sha512()
else:
scriptHelp()
while True:
data = f.read(8192)
if not data:
break
m.update(data)
print "\n\n"
print "The %s hash of file %s is:" % (hashmethod.upper(), filename)
print "\n", m.hexdigest()
if __name__ == "__main__":
inputVerification()