import random
import hmac


def hash_password(password, salthex=None, reps=1000):
    """Compute secure (hash, salthex, reps) triplet for password.

       The password string is required.  The returned salthex and reps
       must be saved and reused to hash any comparison password in
       order for it to match the returned hash.

       The salthex string will be chosen randomly if not provided, and
       if provided must be an even-length string of hexadecimal
       digits, recommended length 16 or
       greater. E.g. salt="([0-9a-z][0-9a-z])*"

       The reps integer must be 1 or greater and should be a
       relatively large number (default 1000) to slow down brute-force
       attacks."""
    
    if not salthex:
        salthex = ''.join([ "%02x" % random.randint(0, 0xFF) 
                            for d in range(0,8) ])

    salt = []
    for p in range(0, len(salthex), 2):
        salt.append(int(salthex[p:p+2], 16))
    salt = bytes(salt)

    if reps < 1:
        reps = 1

    msg = password.encode()
    for r in range(0,reps):
        msg = hmac.HMAC(salt, msg, digestmod='MD5').hexdigest().encode()

    return (msg.decode(), salthex, reps)