application_crypter.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from .application_part import application_part
  2. from .code_key import code_key
  3. from .secret_coder import secret_coder
  4. from .user import user
  5. from .user_loader import user_loader
  6. from .secret_coder import bad_password
  7. class application_crypter(application_part):
  8. """
  9. This is endpoints, which is responsible for encrypting and decrypting
  10. new secrets, to work it require apikey and password. Apikey is used to
  11. load user master crypto key, and password to decrypt that key. Response
  12. which and with success has always encrypted secret and plain decrypted
  13. secret.
  14. """
  15. def encrypt(self, apikey: str, password: str, plain: str) -> dict:
  16. """
  17. This endpoint is requiored to encrypt new secret. It get plain text
  18. which would be encrypted.
  19. Parameters:
  20. apikey (str): ApiKey of the user
  21. password (str): Master password of the user
  22. plain (str): Plain content to encrypt
  23. Returns:
  24. (dict): Result to parse into JSON
  25. """
  26. with self.__database as loader:
  27. target = loader.get_by_apikey(apikey)
  28. if target is None:
  29. return self._fail_no_apikey()
  30. try:
  31. crypted = target.coder(password).encrypt(plain)
  32. except bad_password:
  33. return self._fail_bad_password()
  34. return self.__crypto_response(crypted, plain)
  35. def decrypt(self, apikey: str, password: str, crypted: str) -> dict:
  36. """
  37. This endpoint decrypt given secret. It return plain secret and also
  38. crypted secret.
  39. Parameters:
  40. apikey (str): ApiKey of the user
  41. password (str): Master password of the user
  42. crypted (str): Crypted secret to encode
  43. Returns:
  44. (dict): Result to parse into JSON
  45. """
  46. with self.__database as loader:
  47. target = loader.get_by_apikey(apikey)
  48. if target is None:
  49. return self._fail_no_apikey()
  50. try:
  51. plain = target.coder(password).decrypt(crypted)
  52. except:
  53. return self._fail_bad_password()
  54. return self.__crypto_response(crypted, plain)
  55. def __crypto_response(self, crypted: str, plain: str) -> dict:
  56. """
  57. This return standard success crypto response, which has secret in plan
  58. form, and crypted form. It also of course has information about
  59. success result.
  60. Parameters:
  61. crypted (str): Secret in crypted form
  62. plain (str): Secret in plain form
  63. Returns:
  64. (dict): Result to create JSON response
  65. """
  66. return self._success_response(
  67. crypted = crypted,
  68. plain = plain
  69. )
  70. @property
  71. def __database(self) -> user_loader:
  72. """ This return new handler to user loader. """
  73. return user_loader(self._connector)