import hashlib import os from .secret_properties import secret_properties from .secret import secret class secret_generator(metaclass = secret_properties): def __init__(self, password: str): self.__password = password self.__secret = None @property def password(self) -> str: return self.__password def validate(self, target: secret) -> bool: hashed = target.hashed salt = target.salt target_hashed = self.__generate_hashed(salt) return hashed == target_hashed def __generate_salt(self) -> bytes: properties = self.__class__ result = os.urandom(properties.salt_length) return result def __generate_hashed(self, salt: bytes) -> bytes: properties = self.__class__ rounds = properties.hash_rounds algorithm = properties.hash_algorithm password = self.password.encode("UTF-8") hashed = hashlib.pbkdf2_hmac( algorithm, password, salt, rounds ) return hashed @property def secret(self) -> secret: if self.__secret is not None: return self.__secret salt = self.__generate_salt() hashed = self.__generate_hashed(salt) return secret.build(hashed, salt)