#!/usr/bin/env python3

import hashlib, os
from base64 import encodebytes, decodebytes


# unproudly borrowed from
# http://www.openldap.org/faq/data/cache/347.html
def ssha_encode(password):
    salt = os.urandom(4)
    h = hashlib.sha1(password.encode())
    h.update(salt)
    return b"{SSHA}" + encodebytes(h.digest() + salt)

def ssha_check(challenge_password, password):
    challenge_bytes = decodebytes(challenge_password[6:])
    digest = challenge_bytes[:20]
    salt = challenge_bytes[20:]
    hr = hashlib.sha1(password)
    hr.update(salt)
    return digest == hr.digest()
