/tools/filters/secure_hash_message_digest.py

https://bitbucket.org/cistrome/cistrome-harvard/ · Python · 47 lines · 32 code · 8 blank · 7 comment · 6 complexity · b4d3abe94bccf5217f1934845f146436 MD5 · raw file

  1. #!/usr/bin/env python
  2. #Dan Blankenberg
  3. """
  4. A script for calculating secure hashes / message digests.
  5. """
  6. import optparse, hashlib
  7. from galaxy import eggs
  8. from galaxy.util.odict import odict
  9. HASH_ALGORITHMS = [ 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512' ]
  10. CHUNK_SIZE = 2**20 #1mb
  11. def __main__():
  12. #Parse Command Line
  13. parser = optparse.OptionParser()
  14. parser.add_option( '-a', '--algorithm', dest='algorithms', action='append', type="string", help='Algorithms to use, eg. (md5, sha1, sha224, sha256, sha384, sha512)' )
  15. parser.add_option( '-i', '--input', dest='input', action='store', type="string", help='Input filename' )
  16. parser.add_option( '-o', '--output', dest='output', action='store', type="string", help='Output filename' )
  17. (options, args) = parser.parse_args()
  18. algorithms = odict()
  19. for algorithm in options.algorithms:
  20. assert algorithm in HASH_ALGORITHMS, "Invalid algorithm specified: %s" % ( algorithm )
  21. assert algorithm not in algorithms, "Specify each algorithm only once."
  22. #algorithms[ algorithm ] = locals()[ algorithm ]()
  23. algorithms[ algorithm ] = hashlib.new( algorithm )
  24. assert options.algorithms, "You must provide at least one algorithm."
  25. assert options.input, "You must provide an input filename."
  26. assert options.output, "You must provide an output filename."
  27. input = open( options.input )
  28. while True:
  29. chunk = input.read( CHUNK_SIZE )
  30. if chunk:
  31. for algorithm in algorithms.itervalues():
  32. algorithm.update( chunk )
  33. else:
  34. break
  35. output = open( options.output, 'wb' )
  36. output.write( '#%s\n' % ( '\t'.join( algorithms.keys() ) ) )
  37. output.write( '%s\n' % ( '\t'.join( map( lambda x: x.hexdigest(), algorithms.values() ) ) ) )
  38. output.close()
  39. if __name__=="__main__": __main__()