utils.py 590 B

123456789101112131415161718192021222324
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import hashlib
  4. import binascii
  5. import base64
  6. def str_or_none(obj):
  7. return str(obj) if obj else None
  8. def ldap_hash(password):
  9. """Hash a password for use with LDAP. If the password is already hashed,
  10. do nothing."""
  11. if password and not password.startswith('{SSHA}'):
  12. salt = binascii.hexlify(os.urandom(8))
  13. digest = hashlib.sha1(password.encode() + salt).digest()
  14. return '{SSHA}' + base64.b64encode(digest + salt).decode()
  15. else:
  16. return password
  17. if __name__ == '__main__':
  18. print(ldap_hash('coin'))