Generate CRYPT-SHA512 hashed Passwords for OpenLDAP with Python

I ran into some trouble generating password hashes for users stored in an OpenLDAP directory. OpenLDAP doesn’t do the job for you and passwords are stored the way the come in, even plain text.

SHA512 hashes with pySSHA

Not really keen on diving into the process I integrated the pySSHA into the project which did a great job creating plain old SHA512 hashes. Those work well and I was able to verify the passwords against OpenLDAP.

However the LDAP based client applications did not work that way. Existing accounts used CRYPT-SHA512 hashes rather then just SHA512. pySSHA doesn’t provide for the creation of these hashes.

Discovering passlib

A promising alternative is passlib which seems to be a real multi talent for password hashing and encryption. It even comes with ready made methods to create LDAP/RFC2307 hashes.

While the OpenLDAP directory recognizes them as CRYPT-SHA512 hashes, verification of the passwords failed.

I imagine my relatively poor understanding of LDAP in general has something to do with these problems. Willing to learn. Get in touch if you know more about this :)

Python 3 crypt

Python offers it’s own crypt library which does the job in an elegant and independent fashion. My final solution looks like this:

...
    'userPassword': str('{CRYPT}%s' % crypt.crypt(
        password_plain, 
        crypt.mksalt(
            crypt.METHOD_SHA512
        )
    )).encode('utf-8')
...

With this password verification and LDAP clients are working for me.