Thursday, September 20, 2012

Generate MD5, SHA-1 or SHA-512 UNIX password hashes in Python

When scripting the installation of an Ubuntu server template, I needed to pre-populate the template with a couple of system users that had specific passwords.

My old method of doing this was using openssl:

$ openssl passwd -1

Password: secretstuff
Verifying - Password: secretstuff
$1$IothUf.l$E/4eCqLD9JLdg2et7FurS1


This generates the standard MD5-based password hashes that work in the /etc/shadow file. The string enclosed in the first and second dollar sign indicates the hash method used. The string enclosed in the second and third dollar sign is the password salt used.

If you need other formats, I ended up using Python's built-in crypt module. It supports MD5, SHA-1 and SHA-256 hashes, depending on the value you provide as the "salt" (second parameter):

Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
<<< import crypt
<<< crypt.crypt('secret', '$1$somesalt$')
'$1$somesalt$jezmI5TSY7mVTzHLgsK5L.'
<<< crypt.crypt('secret', '$5$somesalt$')
'$5$somesalt$BY2M0Tw/b.yijagFoMZoeHEQSuk9iqvGNX/dBDdRp8A'
<<< crypt.crypt('secret', '$6$somesalt$')
'$6$somesalt$JX0Uhce8rLRHbaqoSQDYsnTxsqcjCNNcrl79ieTwPGzEhxBEeJcsgDUWIOwc3sDvZN34ZJBWQep7.lcAuSesy/'

No comments:

Post a Comment