# -*- coding: utf-8 -*-
import os
import hashlib
import binascii
import base64


def ldap_hash(password):
    """Hash a password for use with LDAP.  If the password is already hashed,
    do nothing."""
    if password and not password.startswith('{SSHA}'):
        salt = binascii.hexlify(os.urandom(8))
        digest = hashlib.sha1(password.encode() + salt).digest()
        return '{SSHA}' + base64.b64encode(digest + salt).decode()
    else:
        return password


if __name__ == '__main__':
    print(ldap_hash('coin'))
