secret_generator.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import hashlib
  2. import os
  3. from .secret_properties import secret_properties
  4. from .secret import secret
  5. class secret_generator(metaclass = secret_properties):
  6. def __init__(self, password: str):
  7. self.__password = password
  8. self.__secret = None
  9. @property
  10. def password(self) -> str:
  11. return self.__password
  12. def validate(self, target: secret) -> bool:
  13. hashed = target.hashed
  14. salt = target.salt
  15. target_hashed = self.__generate_hashed(salt)
  16. return hashed == target_hashed
  17. def __generate_salt(self) -> bytes:
  18. properties = self.__class__
  19. result = os.urandom(properties.salt_length)
  20. return result
  21. def __generate_hashed(self, salt: bytes) -> bytes:
  22. properties = self.__class__
  23. rounds = properties.hash_rounds
  24. algorithm = properties.hash_algorithm
  25. password = self.password.encode("UTF-8")
  26. hashed = hashlib.pbkdf2_hmac(
  27. algorithm,
  28. password,
  29. salt,
  30. rounds
  31. )
  32. return hashed
  33. @property
  34. def secret(self) -> secret:
  35. if self.__secret is not None:
  36. return self.__secret
  37. salt = self.__generate_salt()
  38. hashed = self.__generate_hashed(salt)
  39. return secret.build(hashed, salt)