Skip to content

Instantly share code, notes, and snippets.

@robballou
Created May 31, 2011 21:06
Show Gist options
  • Save robballou/1001287 to your computer and use it in GitHub Desktop.
Save robballou/1001287 to your computer and use it in GitHub Desktop.
Hash strings using a number of different algorithms
#!/usr/bin/env python
"""
Output hash for a string
If not string is specified, then prompt for one (good for passwords). By default
the script will use SHA1, but you can specify any of the following:
--all (or -a)
--base64 (or -b)
--md5 (or -m)
--sha1
--sha256
--sha512
The 'all' option will output all options.
Requires hashlib (python 2.5)
"""
import hashlib
import base64
from optparse import OptionParser
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('--sha1', dest="sha1", action="store_true", default=False)
parser.add_option('--sha256', dest="sha256", action="store_true", default=False)
parser.add_option('--sha512', dest="sha512", action="store_true", default=False)
parser.add_option('-m', '--md5', dest="md5", action="store_true", default=False)
parser.add_option('-a', '--all', dest="all", action="store_true", default=False)
parser.add_option('-b', '--base64', dest="base64", action="store_true", default=False)
(options, args) = parser.parse_args()
if len(args) == 0:
tmp = raw_input('Text: ')
else:
tmp = ' '.join(args)
all_options_false = True
option_keys = vars(options)
for option in option_keys.keys():
if option_keys[option]:
all_options_false = False
break
if options.base64 or options.all:
s = base64.b64encode(tmp)
print "base64:\t%s" % s
if options.md5 or options.all:
s = hashlib.md5(tmp)
print "md5:\t%s" % s.hexdigest()
if options.sha1 or options.all or all_options_false:
s = hashlib.sha1(tmp)
print "sha1:\t%s" % s.hexdigest()
if options.sha256 or options.all:
s = hashlib.sha256(tmp)
print "sha256:\t%s" % s.hexdigest()
if options.sha512 or options.all:
s = hashlib.sha512(tmp)
print "sha512:\t%s" % s.hexdigest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment