Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/python
- import hashlib
- import sys
- import os
- class Hasher():
- def __init__(self, filepath, hashtype='sha256', chunksize=64):
- if not hashtype in hashlib.algorithms:
- raise ValueError('hashtype not supported')
- self.hashtype = hashtype
- if not os.path.isfile(filepath):
- raise ValueError('file does not exist')
- self.fp = filepath
- self.chunksize = 64
- def hashFile(self):
- self.hasher = hashlib.new(self.hashtype)
- with open(self.fp, 'rb') as file:
- while 1:
- data = file.read(self.chunksize)
- self.hasher.update(data)
- if len(data) < self.chunksize:
- break
- return self.hasher.hexdigest()
- if __name__ == '__main__':
- import argparse
- parser = argparse.ArgumentParser(description='File hasher')
- parser.add_argument('-f', '--file', help='Path to file', action='store', dest='file', default=False)
- parser.add_argument('--hashtype', help='Hash type to use (must be supported by your hashlib version)', action='store', dest='hashtype', default='sha256')
- parser.add_argument('--chunksize', help='Chunk size', action='store', dest='cs', default='64')
- parser.add_argument('--list-types', help='List supported hash types', action='store_true', dest='list', default=False)
- args = parser.parse_args()
- if (len(sys.argv)==1) or ('--help' in sys.argv or '-h' in sys.argv):
- parser.print_help()
- sys.exit(0)
- else:
- pass
- if not args.file and not args.list:
- parser.error('No filepath given')
- else:
- pass
- try:
- chunksize = int(args.cs)
- except ValueError:
- parser.error('Invalid chunksize given')
- if args.list:
- print '[*] Listing supported hash types... '
- for i in hashlib.algorithms:
- print i.upper()
- sys.exit(0)
- try:
- print '[*] Hashing file... ',;sys.stdout.flush()
- hasher = Hasher(args.file, hashtype=args.hashtype.lower())
- hash = hasher.hashFile()
- print '[DONE]'
- print '[*] %s Hash: %s' %(args.hashtype.upper(), hash)
- except ValueError, e:
- if 'file does not exist' in e:
- parser.error('File does not exist')
- elif 'hashtype not supported' in e:
- parser.error('Hash type not supported')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement