password.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import os
  2. import hashlib
  3. class password:
  4. """
  5. This class is responsible for managing passwords and passwords hashes
  6. generating.
  7. """
  8. def __init__(self, target: str, lenght: int = 48) -> None:
  9. """
  10. This is password initialized. It generate new password hash
  11. from the password. Lenght of the hash could be changed.
  12. target: str - Target password
  13. lenght: int - Lenght of the password hash (default: 48)
  14. """
  15. self.__lenght = lenght
  16. self.__target = target
  17. @property
  18. def lenght(self) -> int:
  19. """
  20. This return lenght of the hash.
  21. """
  22. return self.__lenght
  23. @property
  24. def __salt(self) -> str:
  25. """
  26. This return random salt with lenght of the hash."
  27. """
  28. return os.urandom(self.lenght).hex()
  29. @property
  30. def separator(self) -> str:
  31. """
  32. This return separator between salt and hash.
  33. """
  34. return "."
  35. def __generate(self, salt: str) -> str:
  36. """
  37. This generate new hash from the password and salt.
  38. salt: str - Salt to use when generating
  39. return: str - Password hash generated from given salt
  40. """
  41. salted = salt + self.__target
  42. binary = hashlib.shake_256(salted.encode())
  43. hashed = binary.hexdigest(self.lenght)
  44. full = salt + self.separator + hashed
  45. return full
  46. @property
  47. def result(self) -> str:
  48. """
  49. This generate new hash from the password.
  50. return: str - New password hash with random salt
  51. """
  52. return self.__generate(self.__salt)
  53. def validate(self, hashed: str) -> bool:
  54. """
  55. This function validate password hash. When passwords match, then
  56. return True, when password from the class not match with given hash,
  57. then return False.
  58. hashed: str - Password hash to check
  59. return: bool - True when passwords match, False if not
  60. """
  61. position = hashed.find(self.separator)
  62. if position == -1:
  63. return False
  64. salt = hashed[:position]
  65. full = hashed[position + len(self.separator):]
  66. if len(salt) != len(full):
  67. return False
  68. if len(full) != self.lenght * 2:
  69. return False
  70. return self.__generate(salt) == hashed