import binascii
import hashlib


class PBKDF2Encryption:
    algorithm_name = "PBKDF2WithHmacSHA512"
    iterations = 10000
    derived_key_length = 128
    pbkdf2_prefix = "!PBKDF2!"
    salt_byte = b'BMPC_PBKDF2_HASH_'

    @staticmethod
    def hash_string(str_to_hash):
        try:
            hashed_str = PBKDF2Encryption.get_hashed_string(str_to_hash.encode('utf-8'), PBKDF2Encryption.salt_byte,
                                                            PBKDF2Encryption.iterations,
                                                            PBKDF2Encryption.derived_key_length)
            hashed_str_with_prefix = PBKDF2Encryption.pbkdf2_prefix + binascii.hexlify(hashed_str).decode('utf-8')
            return hashed_str_with_prefix.upper()
        except Exception as e:
            emsg = "Hashing string failed to accrue PBKDF2WithHmacSHA512 algorithm: " + str(e)
            raise Exception(emsg)

    @staticmethod
    def get_hashed_string(password, salt, iterations, derived_key_length):
        return hashlib.pbkdf2_hmac('sha512', password, salt, iterations, derived_key_length)

    @staticmethod
    def ByteArrayToString(byte_array):
        out = ""
        for i in range(len(byte_array)):
            s = hex(byte_array[i])[2:].zfill(2)
            out += s
        return out
