Skip to content

Instantly share code, notes, and snippets.

@pjfoley
Created July 13, 2013 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjfoley/5989653 to your computer and use it in GitHub Desktop.
Save pjfoley/5989653 to your computer and use it in GitHub Desktop.
# encoding: utf-8
# References:
# http://serverfault.com/questions/330069/how-to-create-an-sha-512-hashed-password-for-shadow
# http://docs.python.org/dev/library/crypt.html#module-crypt
import crypt
import sys
import argparse
import string
import random
# Tuple == (Hash Method, Salt Length, Magic String, Hashed Password Length)
supported_hashes=[('crypt',2,'',13), ('md5',8,'$1$',22), ('sha256',16,'$5$',43), ('sha512',16,'$6$',86)]
# Extra valid hash functions for checking user input
m_hashing_methods = [z[0] for z in supported_hashes]
def main():
parser = argparse.ArgumentParser(description='Generate an encrypted password.')
parser.add_argument('--hash', default='sha512', choices=m_hashing_methods, help='Which Hash function to use')
parser.add_argument('-s', '--salt', help='Salt to use with Password')
parser.add_argument('-d', '--debug', action='store_true', help='Output some useful Debug Information')
parser.add_argument('password')
args = parser.parse_args()
# Find the tuple with correct values for hashing function
l_crypt_tuple = [x for x in supported_hashes if x[0] == args.hash]
salt_length = l_crypt_tuple[0][1]
hash_type = l_crypt_tuple[0][2]
expected_password_length = l_crypt_tuple[0][3]
if not args.salt:
salt_word = ''.join((random.choice(string.letters + string.digits + string.punctuation.replace("$","").replace("'",""))) for x in range(salt_length))
else:
salt_word = args.salt
l_result = crypt.crypt(args.password, "".join((hash_type, salt_word)))
if args.debug:
print "Salt Used: ", salt_word
if salt_length > len(salt_word):
print "Your Salt is shorter than the required one of", salt_length, "characters."
if args.debug:
password_length = len(l_result) - salt_length - len(hash_type) - 1
print "Salt Length: ", len(salt_word), "should be", salt_length
print "Password Hash: ", password_length
print l_result
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment