import hmac
import hashlib
import struct


def bin_pbkdf2_hmac(hashname, password, salt, rounds, dklen=None):
    """Password-Based Key Derivation Function (PBKDF) 2"""
    h = hmac.new(key=password, digestmod=lambda d=b'': hashlib.new(hashname, d))
    dklen = h.digest_size if dklen is None else dklen
    def prf(data):
        hm = h.copy()
        hm.update(data)
        return bytearray(hm.digest())
    key = bytearray()
    i = 1
    while len(key) < dklen:
        T = U = prf(salt + struct.pack('>i', i))
        for _ in range(rounds - 1):
            U = prf(U)
            T = bytearray(x ^ y for x, y in zip(T, U))
        key += T
        i += 1
    return bytes(key[:dklen])