PageRenderTime 27ms CodeModel.GetById 18ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/filters/secure_hash_message_digest.py

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