Skip to content

Instantly share code, notes, and snippets.

@lorin
Created June 5, 2013 19:24
Show Gist options
  • Save lorin/5716491 to your computer and use it in GitHub Desktop.
Save lorin/5716491 to your computer and use it in GitHub Desktop.
Generate a password hash suitable for /etc/shadow. Warning: Gives incorrect value on OS X.
#!/usr/bin/env python
"""
Generate a password hash, suitable for /etc/shadow
Inspired by this code from OpenStack:
https://github.com/openstack/nova/blob/stable/grizzly/nova/virt/disk/api.py#L549
Usage:
mkpasswd <passwd> [--algo=<hash>]
Options:
--algo=<hash> One of: SHA-512, SHA-256, MD5, DES [default: SHA-256]
"""
from docopt import docopt
import crypt
import random
def generate_salt():
salt_set = ('abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789./')
salt = 16 * ' '
return ''.join([random.choice(salt_set) for c in salt])
def main(passwd, algo):
# encryption algo - id pairs for crypt()
algos = {'SHA-512': '$6$', 'SHA-256': '$5$', 'MD5': '$1$', 'DES': ''}
salt = generate_salt()
result = crypt.crypt(passwd, algos[algo] + salt)
return result
if __name__ == '__main__':
args = docopt(__doc__)
pw = main(passwd=args['<passwd>'], algo=args['--algo'])
print pw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment