Skip to content

Instantly share code, notes, and snippets.

@ljjjustin
Forked from lorin/mkpasswd.py
Created May 11, 2022 08:14
Show Gist options
  • Save ljjjustin/d9392cefdd00f54f1336cd24b47da1c7 to your computer and use it in GitHub Desktop.
Save ljjjustin/d9392cefdd00f54f1336cd24b47da1c7 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