def decrypt_payload(payload, config, _params=None): """Decrypt some fields of a JSON payload using the given configuration.""" try: json_payload = payload if type(payload) is dict else json.loads( payload) for elem, target in config.paths["$"].to_decrypt.items(): try: node = get_node(json_payload, elem) cipher_text = decode_value( node.pop(config.encrypted_value_field_name), config.data_encoding) if not _params: try: encrypted_key = node.pop( config.encrypted_key_field_name) iv = node.pop(config.iv_field_name) except KeyError: raise EncryptionError( "Encryption field(s) missing in payload.") oaep_digest_algo = node.pop( config.oaep_padding_digest_algorithm_field_name, config.oaep_padding_digest_algorithm) _remove_fingerprint_from_node(node, config) params = SessionKeyParams(config, encrypted_key, iv, oaep_digest_algo) else: params = _params cleanup_node(json_payload, elem, target) try: update_node( json_payload, target, _decrypt_bytes(params.key, params.iv_spec, cipher_text)) except KeyError: raise EncryptionError("Field '" + target + "' not found!") except KeyError: pass # encrypted data node not found, nothing to decrypt return json_payload except json.JSONDecodeError: # not a json response - return it as is return payload except (IOError, ValueError, TypeError) as e: raise EncryptionError("Payload decryption failed!", e)
def test_cleanup_node_empty_target(self): sample_json = self.__get_sample_json() del sample_json["node1"]["node2"]["colour"] del sample_json["node1"]["node2"]["shape"] del sample_json["node1"]["node2"]["position"] node = to_test.cleanup_node(sample_json, "node1.node2", None) self.assertIsInstance(node, dict, "Not a dictionary") self.assertDictEqual({"node1": {}}, node) self.assertDictEqual({"node1": {}}, sample_json) sample_json = self.__get_sample_json() del sample_json["node1"]["node2"]["colour"] del sample_json["node1"]["node2"]["shape"] del sample_json["node1"]["node2"]["position"] node = to_test.cleanup_node(sample_json, "node1.node2", "") self.assertIsInstance(node, dict, "Not a dictionary") self.assertDictEqual({"node1": {}}, node) self.assertDictEqual({"node1": {}}, sample_json)