secret.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from .secret_properties import secret_properties
  2. class secret(metaclass = secret_properties):
  3. def __init__(self, token: str):
  4. if not self.__check(token):
  5. raise Exception("Token is not valid.")
  6. self.__token = token
  7. def clone(self):
  8. return secret(self.token)
  9. def build(hashed: bytes, salt: bytes):
  10. separator = secret.salt_separator
  11. result = secret(hashed.hex() + separator + salt.hex())
  12. return result
  13. @property
  14. def token(self) -> str:
  15. return self.__token
  16. @property
  17. def hashed(self) -> bytes:
  18. properties = self.__class__
  19. separator = properties.salt_separator
  20. splited = self.token.split(separator)
  21. return bytes.fromhex(splited[0])
  22. @property
  23. def salt(self) -> bytes:
  24. properties = self.__class__
  25. separator = properties.salt_separator
  26. splited = self.token.split(separator)
  27. return bytes.fromhex(splited[-1])
  28. def __str__(self) -> str:
  29. return self.token
  30. def __check(self, token: str) -> bool:
  31. properties = self.__class__
  32. separator = properties.salt_separator
  33. splited = token.split(separator)
  34. if len(splited) != 2:
  35. return False
  36. hashed = splited[0]
  37. salt = splited[1]
  38. if len(hashed) != properties.hash_hex_length:
  39. return False
  40. if len(salt) / 2 != properties.salt_length:
  41. return False
  42. return True