Advertisement
The_Defalt

hasher.py

Dec 21st, 2017
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. #! /usr/bin/python
  2.  
  3. import hashlib
  4. import sys
  5. import os
  6.  
  7. class Hasher():
  8.     def __init__(self, filepath, hashtype='sha256', chunksize=64):
  9.         if not hashtype in hashlib.algorithms:
  10.             raise ValueError('hashtype not supported')
  11.         self.hashtype = hashtype
  12.  
  13.         if not os.path.isfile(filepath):
  14.             raise ValueError('file does not exist')
  15.         self.fp = filepath
  16.  
  17.         self.chunksize = 64
  18.  
  19.     def hashFile(self):
  20.         self.hasher = hashlib.new(self.hashtype)
  21.         with open(self.fp, 'rb') as file:
  22.             while 1:
  23.                 data = file.read(self.chunksize)
  24.                 self.hasher.update(data)
  25.                 if len(data) < self.chunksize:
  26.                     break
  27.         return self.hasher.hexdigest()
  28.  
  29. if __name__ == '__main__':
  30.     import argparse
  31.     parser = argparse.ArgumentParser(description='File hasher')
  32.     parser.add_argument('-f', '--file', help='Path to file', action='store', dest='file', default=False)
  33.     parser.add_argument('--hashtype', help='Hash type to use (must be supported by your hashlib version)', action='store', dest='hashtype', default='sha256')
  34.     parser.add_argument('--chunksize', help='Chunk size', action='store', dest='cs', default='64')
  35.     parser.add_argument('--list-types', help='List supported hash types', action='store_true', dest='list', default=False)
  36.     args = parser.parse_args()
  37.     if (len(sys.argv)==1) or ('--help' in sys.argv or '-h' in sys.argv):
  38.         parser.print_help()
  39.         sys.exit(0)
  40.     else:
  41.         pass
  42.     if not args.file and not args.list:
  43.         parser.error('No filepath given')
  44.     else:
  45.         pass
  46.     try:
  47.         chunksize = int(args.cs)
  48.     except ValueError:
  49.         parser.error('Invalid chunksize given')
  50.     if args.list:
  51.         print '[*] Listing supported hash types... '
  52.         for i in hashlib.algorithms:
  53.             print i.upper()
  54.         sys.exit(0)
  55.     try:
  56.         print '[*] Hashing file... ',;sys.stdout.flush()
  57.         hasher = Hasher(args.file, hashtype=args.hashtype.lower())
  58.         hash = hasher.hashFile()
  59.         print '[DONE]'
  60.         print '[*] %s Hash: %s' %(args.hashtype.upper(), hash)
  61.     except ValueError, e:
  62.         if 'file does not exist' in e:
  63.             parser.error('File does not exist')
  64.         elif 'hashtype not supported' in e:
  65.             parser.error('Hash type not supported')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement