import string
import random
import hashlib


def hash_password(password, salt=None):
    """Hash a password.

    :param password: the cleartext password
    :type password: str
    :param salt: the optional salt (randomly generated, if None)
    :type salt: str

    :returns: the hashed password
    :rtype: str"""
    if salt is None:
        salt_pool = string.ascii_letters + string.digits
        salt = ''.join(random.choice(salt_pool) for x in range(32))
    pass_and_salt = '%s%s' % (salt, password)
    pass_and_salt = pass_and_salt.encode('utf-8', 'ignore')
    hash_ = hashlib.sha512(pass_and_salt)
    return '$%s$%s' % (salt, hash_.hexdigest())