from .application_part import application_part from .code_key import code_key from .secret_coder import secret_coder from .user import user from .user_loader import user_loader from .secret_coder import bad_password class application_crypter(application_part): """ This is endpoints, which is responsible for encrypting and decrypting new secrets, to work it require apikey and password. Apikey is used to load user master crypto key, and password to decrypt that key. Response which and with success has always encrypted secret and plain decrypted secret. """ def encrypt(self, apikey: str, password: str, plain: str) -> dict: """ This endpoint is requiored to encrypt new secret. It get plain text which would be encrypted. Parameters: apikey (str): ApiKey of the user password (str): Master password of the user plain (str): Plain content to encrypt Returns: (dict): Result to parse into JSON """ with self.__database as loader: target = loader.get_by_apikey(apikey) if target is None: return self._fail_no_apikey() try: crypted = target.coder(password).encrypt(plain) except bad_password: return self._fail_bad_password() return self.__crypto_response(crypted, plain) def decrypt(self, apikey: str, password: str, crypted: str) -> dict: """ This endpoint decrypt given secret. It return plain secret and also crypted secret. Parameters: apikey (str): ApiKey of the user password (str): Master password of the user crypted (str): Crypted secret to encode Returns: (dict): Result to parse into JSON """ with self.__database as loader: target = loader.get_by_apikey(apikey) if target is None: return self._fail_no_apikey() try: plain = target.coder(password).decrypt(crypted) except: return self._fail_bad_password() return self.__crypto_response(crypted, plain) def __crypto_response(self, crypted: str, plain: str) -> dict: """ This return standard success crypto response, which has secret in plan form, and crypted form. It also of course has information about success result. Parameters: crypted (str): Secret in crypted form plain (str): Secret in plain form Returns: (dict): Result to create JSON response """ return self._success_response( crypted = crypted, plain = plain ) @property def __database(self) -> user_loader: """ This return new handler to user loader. """ return user_loader(self._connector)