path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
ciphey.ciphey/main
Modified
Ciphey~Ciphey
2c6425a01270c7d3ce085e212628e7ed45cfc34c
help menu prints on no argument inputs
<12>:<add> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <del> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" -d true -c true
<s> help="Adds a module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" -d true -c true <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is not None: <32> dirs = AppDirs("Ciphey", "C</s>
===========below chunk 0=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 print(f"The settings.yml file location should be {dirs.user_config_dir}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) else: config.load_file(cfg_arg) # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) config.load_modules() # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") output_format = kwargs["bytes</s> ===========below chunk 1=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s>_input"] is not None: config.update_format("in", "bytes") output_format = kwargs["bytes_output"] if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.load_objs() logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs</s> ===========below chunk 2=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s>"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.iface._registry/Registry._real_register
Modified
Ciphey~Ciphey
2ce80a1152e03d8f0ea6b153fe8f64dd0d7d649d
Fixed octal
<0>:<add> name = input_type.__name__.lower() <add> name_target = self._names[name] = (input_type, set()) <del> name_target = self._names[input_type.__name__.lower()] = (input_type, set())
# module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: <0> name_target = self._names[input_type.__name__.lower()] = (input_type, set()) <1> <2> if issubclass(input_type, Targeted): <3> target = input_type.getTarget() <4> else: <5> target = None <6> <7> if issubclass(input_type, Searcher): <8> module_type = module_base = Searcher <9> module_args = () <10> else: <11> module_type: Optional[Type] = None <12> module_base = None <13> <14> # Work out what module type this is <15> if len(args) == 0: <16> for i in input_type.__orig_bases__: <17> if module_type is not None: <18> raise TypeError(f"Type derived from multiple registrable base classes {i} and {module_type}") <19> module_base = get_origin(i) <20> if module_base not in self._modules: <21> continue <22> module_type = i <23> else: <24> for i in self._modules: <25> if not issubclass(input_type, i): <26> continue <27> if module_type is not None: <28> raise TypeError(f"Type derived from multiple registrable base classes {i} and {module_type}") <29> module_type = i <30> if module_type is None: <31> raise TypeError("No registrable base class") <32> <33> # Now handle the difference between register and register_multi <34> if len(args) == 0: <35> if module_base is None: <36> raise TypeError("No type argument given") <37> self._register_one(input_type, module_base, get_args(module_type)) <38> name_target[1].add(module_base) <39> else: <40> if module_base is not None: <41> raise TypeError(f"Redundant type argument for {module_type}") <42> module_base = module_type </s>
===========below chunk 0=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 # Correct missing brackets if not isinstance(module_args, tuple): module_args = (module_args,) self._register_one(input_type, module_base, module_args) name_target[1].add(module_type[module_args]) name_target[1].add(module_type) if target is not None and issubclass(module_base, Targeted): self._targets.setdefault(target, {}).setdefault(module_type, []).append(input_type) return input_type ===========unchanged ref 0=========== at: ciphey.iface._modules Targeted() Searcher(config: Config) at: ciphey.iface._registry.Registry RegElem = Union[List[Type], Dict[Type, "RegElem"]] _reg: Dict[Type, RegElem] = {} _names: Dict[str, Tuple[Type, Set[Type]]] = {} _targets: Dict[str, Dict[Type, List[Type]]] = {} _modules = {Checker, Cracker, Decoder, ResourceLoader, Searcher} _register_one(input_type, module_base, module_args) at: typing get_origin(tp: Any) -> Optional[Any] get_args(tp: Any) -> Tuple[Any, ...] Type = _alias(type, 1, inst=False, name='Type')
ciphey.basemods.Decoders.octal/Octal.decode
Modified
Ciphey~Ciphey
2ce80a1152e03d8f0ea6b153fe8f64dd0d7d649d
Fixed octal
<6>:<add> str_converted = bytes() <del> str_converted = "" <8>:<add> str_converted += int(octal_char, 8) <del> str_converted += chr(int(octal_char, 8))
# module: ciphey.basemods.Decoders.octal @registry.register + class Octal(ciphey.iface.Decoder[str, bytes]): - class Octal(ciphey.iface.Decoder[bytes, str]): + def decode(self, text: str) -> Optional[bytes]: - def decode(self, text: bytes) -> Optional[str]: <0> print("Attempting octal") <1> """ <2> It takes an octal string and return a string <3> :octal_str: octal str like "110 145 154" <4> """ <5> logger.trace("Attempting Octal") <6> str_converted = "" <7> for octal_char in text.split(" "): <8> str_converted += chr(int(octal_char, 8)) <9> logger.trace(f"Octal returns {str_converted}") <10> return str_converted <11>
===========unchanged ref 0=========== at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] ===========changed ref 0=========== # module: ciphey.iface._registry class Registry: + def get_all_names(self) -> List[str]: + return list(self._names.keys()) + ===========changed ref 1=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: + name = input_type.__name__.lower() + name_target = self._names[name] = (input_type, set()) - name_target = self._names[input_type.__name__.lower()] = (input_type, set()) if issubclass(input_type, Targeted): target = input_type.getTarget() else: target = None if issubclass(input_type, Searcher): module_type = module_base = Searcher module_args = () else: module_type: Optional[Type] = None module_base = None # Work out what module type this is if len(args) == 0: for i in input_type.__orig_bases__: if module_type is not None: raise TypeError(f"Type derived from multiple registrable base classes {i} and {module_type}") module_base = get_origin(i) if module_base not in self._modules: continue module_type = i else: for i in self._modules: if not issubclass(input_type, i): continue if module_type is not None: raise TypeError(f"Type derived from multiple registrable base classes {i} and {module_type}") module_type = i if module_type is None: raise TypeError("No registrable base class") # Now handle the difference between register and register_multi if len(args) == 0: if module_base is None: raise TypeError("No type argument given") self._register_one(input_type, module_base, get_args(module_type)) name_target[1].add(module_base) else: if module_base is not None: raise TypeError(f"Redundant type argument for {module_type}") module_base = module_type for module_args in args:</s> ===========changed ref 2=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 <s>"Redundant type argument for {module_type}") module_base = module_type for module_args in args: # Correct missing brackets if not isinstance(module_args, tuple): module_args = (module_args,) self._register_one(input_type, module_base, module_args) name_target[1].add(module_type[module_args]) name_target[1].add(module_type) if target is not None and issubclass(module_base, Targeted): self._targets.setdefault(target, {}).setdefault(module_type, []).append(input_type) return input_type
ciphey.basemods.Decoders.octal/Octal.decode
Modified
Ciphey~Ciphey
94504aa4538c9de70ea68f6236dcb33383bb9553
Added concat octal
<0>:<del> print("Attempting octal") <5>:<del> logger.trace("Attempting Octal") <6>:<add> str_converted = [] <del> str_converted = bytes() <7>:<add> octal_seq = text.split(" ") <del> for octal_char in text.split(" "): <8>:<add> if len(octal_seq) == 1: <add> # Concatted octal must be formed of octal triplets <add> if len(text) % 3 != 0: <add> return None <add> octal_seq = [text[i:i+3] for i in range(0, len(text), 3)] <add> logger.trace(f"Trying chunked octal {octal_seq}") <add> try: <add> for octal_char in octal_seq: <add> if len(octal_char) > 3: <add> logger.trace(f"Octal subseq too long") <add> n = int(octal_char, 8) <del> str_converted += int(octal_char, 8) <9>:<add> if n < 0: # n cannot be greater than 255, as we checked that with the earlier length check <add> logger.trace(f"Non octal char {octal_char}") <add> return None <add> str_converted.
# module: ciphey.basemods.Decoders.octal @registry.register class Octal(ciphey.iface.Decoder[str, bytes]): def decode(self, text: str) -> Optional[bytes]: <0> print("Attempting octal") <1> """ <2> It takes an octal string and return a string <3> :octal_str: octal str like "110 145 154" <4> """ <5> logger.trace("Attempting Octal") <6> str_converted = bytes() <7> for octal_char in text.split(" "): <8> str_converted += int(octal_char, 8) <9> logger.trace(f"Octal returns {str_converted}") <10> return str_converted <11>
===========unchanged ref 0=========== at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U]
tests.test_main/test_base64_caesar
Modified
Ciphey~Ciphey
c290cd755b9b33cac09010fb488b328b4f37f9c1
Tests successfully run. Reduced hash weight
<2>:<add> main, <add> [ <add> "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100
# module: tests.test_main def test_base64_caesar(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, ["SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGNhdA==", "-vvv"], <3> ) <4> assert result.exit_code == 0 <5> assert "dog" in result.output <6>
ciphey.basemods.Decoders.hash/HashBuster.priority
Modified
Ciphey~Ciphey
c290cd755b9b33cac09010fb488b328b4f37f9c1
Tests successfully run. Reduced hash weight
<0>:<add> return 0.05 <del> return 0.4
# module: ciphey.basemods.Decoders.hash @registry.register class HashBuster(ciphey.iface.Decoder[str, bytes]): @staticmethod def priority() -> float: <0> return 0.4 <1>
===========unchanged ref 0=========== at: ciphey.iface._modules.Decoder priority() -> float ===========changed ref 0=========== # module: tests.test_main def test_base64_caesar(): runner = CliRunner() result = runner.invoke( + main, + [ + "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100 01011000 01010001 01100111 01010011 01010011 01000010 01101000 01100010 01001000 01001110 01110110 01001001 01000111 01010010 01110110 01001001 01000111 01101000 01101000 01100011 01001000 01000010 01101100 01100010 01101001 01000010 00110000 01100010 01111001 01000010 01101100 01100010 01101101 01110000 01110110 01100101 01010011 01000010 00110011 01011001 01010111 01111000 01110010 01100011 01110111 00111101 00111101", + "-vvv", + ], - main, ["SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbG</s> ===========changed ref 1=========== # module: tests.test_main def test_base64_caesar(): # offset: 1 <s> ["SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGNhdA==", "-vvv"], ) assert result.exit_code == 0 assert "dog" in result.output
ciphey.basemods.Checkers.brandon/Brandon.__init__
Modified
Ciphey~Ciphey
fd29aa32a3b061a26485cf9943aa0bb02b262dac
Brandon checker now works on small inputs
<5>:<add> print(phases) <7>:<add> print(self.thresholds_phase1) <8>:<add> print(self.thresholds_phase2)
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def __init__(self, config: ciphey.iface.Config): <0> # Suppresses warning <1> super().__init__(config) <2> self.mh = mh.mathsHelper() <3> <4> phases = config.get_resource(self._params()["phases"]) <5> <6> self.thresholds_phase1 = phases["1"] <7> self.thresholds_phase2 = phases["2"] <8> self.top1000Words = config.get_resource(self._params().get("top1000")) <9> self.wordlist = config.get_resource(self._params()["wordlist"]) <10> self.stopwords = config.get_resource(self._params().get("stopwords")) <11> <12> self.len_phase1 = len(self.thresholds_phase1) <13> self.len_phase2 = len(self.thresholds_phase2) <14>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._config.Config verbosity: int = 0 searcher: str = "perfection" params: Dict[str, Dict[str, Union[str, List[str]]]] = {} format: Dict[str, str] = {"in": "str", "out": "str"} modules: List[str] = [] checker: str = "brandon" default_dist: str = "cipheydists::dist::twist" timeout: Optional[int] = None _inst: Dict[type, Any] = {} objs: Dict[str, Any] = {} cache: Cache = Cache() get_resource(res_name: str, t: Optional[Type]=None) -> Any at: ciphey.iface._modules.Checker __init__(config: Config) __init__(self, config: Config) at: ciphey.iface._modules.ConfigurableModule _params() at: ciphey.mathsHelper mathsHelper()
ciphey.basemods.Checkers.brandon/Brandon.check
Modified
Ciphey~Ciphey
fd29aa32a3b061a26485cf9943aa0bb02b262dac
Brandon checker now works on small inputs
<36>:<add> logger.trace("using trace")
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: <0> """Checks to see if the text is in English <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> text -> The text we use to perform analysis on <6> <7> Returns: <8> bool -> True if the text is English, False otherwise. <9> <10> """ <11> logger.trace(f'In Language Checker with "{text}"') <12> text = self.clean_text(text) <13> logger.trace(f'Text split to "{text}"') <14> if text == "": <15> return None <16> <17> length_text = len(text) <18> <19> # "Phase 1": {0: {"check": 0.02}, 110: {"stop": 0.15}, 150: {"stop": 0.28}} <20> <21> # Phase 1 checking <22> <23> what_to_use = {} <24> <25> # this code decides what checker / threshold to use <26> # if text is over or equal to maximum size, just use the maximum possible checker <27> what_to_use = self.calculateWhatChecker( <28> length_text, self.thresholds_phase1.keys() <29> ) <30> logger.trace(f"What to use is {what_to_use}") <31> logger.trace(self.thresholds_phase1) <32> what_to_use = self.thresholds_phase1[str(what_to_use)] <33> # def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: <34> if "check" in what_to_use: <35> # perform check 1k words <36> result = self.checker( <37> text, what</s>
===========below chunk 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: # offset: 1 ) logger.trace(f"The result from check 1k words is {result}") elif "stop" in what_to_use: # perform stopwords result = self.checker( text, what_to_use["stop"], length_text, self.stopwords ) logger.trace(f"The result from check stopwords is {result}") else: logger.debug(f"It is neither stop or check, but instead {what_to_use}") # return False if phase 1 fails if not result: return None else: what_to_use = self.calculateWhatChecker( length_text, self.thresholds_phase2.keys() ) what_to_use = self.thresholds_phase2[str(what_to_use)] result = self.checker( text, what_to_use["dict"], length_text, self.wordlist ) logger.trace(f"Result of dictionary checker is {result}") return "" if result else None ===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon wordlist: set clean_text(text: str) -> set checker(text: str, threshold: float, text_length: int, var: set) -> bool calculateWhatChecker(self, length_text, key) calculateWhatChecker(length_text, key) at: ciphey.basemods.Checkers.brandon.Brandon.__init__ self.thresholds_phase1 = phases["1"] self.thresholds_phase2 = phases["2"] self.top1000Words = config.get_resource(self._params().get("top1000")) self.wordlist = config.get_resource(self._params()["wordlist"]) at: ciphey.iface._config.Config get_resource(res_name: str, t: Optional[Type]=None) -> Any at: ciphey.iface._modules.Checker check(self, text: T) -> Optional[str] at: ciphey.iface._modules.ConfigurableModule _params() ===========changed ref 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def __init__(self, config: ciphey.iface.Config): # Suppresses warning super().__init__(config) self.mh = mh.mathsHelper() phases = config.get_resource(self._params()["phases"]) + print(phases) self.thresholds_phase1 = phases["1"] + print(self.thresholds_phase1) self.thresholds_phase2 = phases["2"] + print(self.thresholds_phase2) self.top1000Words = config.get_resource(self._params().get("top1000")) self.wordlist = config.get_resource(self._params()["wordlist"]) self.stopwords = config.get_resource(self._params().get("stopwords")) self.len_phase1 = len(self.thresholds_phase1) self.len_phase2 = len(self.thresholds_phase2)
ciphey.basemods.Checkers.brandon/Brandon.calculateWhatChecker
Modified
Ciphey~Ciphey
fd29aa32a3b061a26485cf9943aa0bb02b262dac
Brandon checker now works on small inputs
<19>:<add> logger.trace( <add> f"Length of text is max therefore what to use is {what_to_use}" <add> ) <21>:<add> logger.trace(f"{_keys}") <22>:<add> logger.trace(f"counter -1 is {_keys[counter -1]}") <add> logger.trace(f"{length_text} <= {i}") <add> # [0, 110, 150] <add> if i <= length_text: <del> if counter != 0: <23>:<del> if _keys[counter - 1] <= length_text <= i: <24>:<add> what_to_use = i <del> what_to_use = i <25>:<add> logger.trace(f"{length_text} <= {i}") <add> logger.trace(f"else what to use is {what_to_use}")
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def calculateWhatChecker(self, length_text, key): <0> """Calculates what threshold / checker to use <1> <2> If the length of the text is over the maximum sentence length, use the last checker / threshold <3> Otherwise, traverse the keys backwards until we find a key range that does not fit. <4> So we traverse backwards and see if the sentence length is between current - 1 and current <5> In this way, we find the absolute lowest checker / percentage threshold. <6> We traverse backwards because if the text is longer than the max sentence length, we already know. <7> In total, the keys are only 5 items long or so. It is not expensive to move backwards, nor is it expensive to move forwards. <8> <9> Args: <10> length_text -> The length of the text <11> key -> What key we want to use. I.E. Phase1 keys, Phase2 keys. <12> Returns: <13> what_to_use -> the key of the lowest checker.""" <14> <15> _keys = list(key) <16> _keys = list(map(int, _keys)) <17> if length_text >= int(_keys[-1]): <18> what_to_use = key[_keys[-1]] <19> else: <20> # this algorithm finds the smallest possible fit for the text <21> for counter, i in reversed(list(enumerate(_keys))): <22> if counter != 0: <23> if _keys[counter - 1] <= length_text <= i: <24> what_to_use = i <25> return what_to_use <26>
===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon checker(text: str, threshold: float, text_length: int, var: set) -> bool at: ciphey.basemods.Checkers.brandon.Brandon.__init__ self.thresholds_phase2 = phases["2"] self.wordlist = config.get_resource(self._params()["wordlist"]) at: ciphey.basemods.Checkers.brandon.Brandon.check text = self.clean_text(text) length_text = len(text) ===========changed ref 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def __init__(self, config: ciphey.iface.Config): # Suppresses warning super().__init__(config) self.mh = mh.mathsHelper() phases = config.get_resource(self._params()["phases"]) + print(phases) self.thresholds_phase1 = phases["1"] + print(self.thresholds_phase1) self.thresholds_phase2 = phases["2"] + print(self.thresholds_phase2) self.top1000Words = config.get_resource(self._params().get("top1000")) self.wordlist = config.get_resource(self._params()["wordlist"]) self.stopwords = config.get_resource(self._params().get("stopwords")) self.len_phase1 = len(self.thresholds_phase1) self.len_phase2 = len(self.thresholds_phase2) ===========changed ref 1=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: """Checks to see if the text is in English Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: text -> The text we use to perform analysis on Returns: bool -> True if the text is English, False otherwise. """ logger.trace(f'In Language Checker with "{text}"') text = self.clean_text(text) logger.trace(f'Text split to "{text}"') if text == "": return None length_text = len(text) # "Phase 1": {0: {"check": 0.02}, 110: {"stop": 0.15}, 150: {"stop": 0.28}} # Phase 1 checking what_to_use = {} # this code decides what checker / threshold to use # if text is over or equal to maximum size, just use the maximum possible checker what_to_use = self.calculateWhatChecker( length_text, self.thresholds_phase1.keys() ) logger.trace(f"What to use is {what_to_use}") logger.trace(self.thresholds_phase1) what_to_use = self.thresholds_phase1[str(what_to_use)] # def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: if "check" in what_to_use: # perform check 1k words + logger.trace("using trace") result = self.checker( text, what_to_use["check"], length_text, self.top1000Words ) logger.trace</s> ===========changed ref 2=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: # offset: 1 <s> text, what_to_use["check"], length_text, self.top1000Words ) logger.trace(f"The result from check 1k words is {result}") elif "stop" in what_to_use: # perform stopwords + logger.trace("using trace") result = self.checker( text, what_to_use["stop"], length_text, self.stopwords ) logger.trace(f"The result from check stopwords is {result}") + elif "dict" in what_to_use: + logger.trace("in dict") + result = self.checker(text, what_to_use["dict"], length_text, self.wordlist) + # If result is None, no point doing it again in phase2 + if not result: + return None else: logger.debug(f"It is neither stop or check, but instead {what_to_use}") # return False if phase 1 fails if not result: return None else: what_to_use = self.calculateWhatChecker( length_text, self.thresholds_phase2.keys() ) what_to_use = self.thresholds_phase2[str(what_to_use)] - result = self.checker( + result = self.checker(text, what_to_use["dict"], length_text, self.wordlist) - text, what_to_use["dict"], length_text, self.wordlist - ) logger
ciphey.basemods.Checkers.brandon/Brandon.__init__
Modified
Ciphey~Ciphey
084cc94ff9b3424a03e8cd966e4cb5b6fe5c7424
removing logs
<5>:<del> print(phases) <8>:<del> print(self.thresholds_phase1) <10>:<del> print(self.thresholds_phase2)
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def __init__(self, config: ciphey.iface.Config): <0> # Suppresses warning <1> super().__init__(config) <2> self.mh = mh.mathsHelper() <3> <4> phases = config.get_resource(self._params()["phases"]) <5> print(phases) <6> <7> self.thresholds_phase1 = phases["1"] <8> print(self.thresholds_phase1) <9> self.thresholds_phase2 = phases["2"] <10> print(self.thresholds_phase2) <11> self.top1000Words = config.get_resource(self._params().get("top1000")) <12> self.wordlist = config.get_resource(self._params()["wordlist"]) <13> self.stopwords = config.get_resource(self._params().get("stopwords")) <14> <15> self.len_phase1 = len(self.thresholds_phase1) <16> self.len_phase2 = len(self.thresholds_phase2) <17>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._config.Config verbosity: int = 0 searcher: str = "perfection" params: Dict[str, Dict[str, Union[str, List[str]]]] = {} format: Dict[str, str] = {"in": "str", "out": "str"} modules: List[str] = [] checker: str = "brandon" default_dist: str = "cipheydists::dist::twist" timeout: Optional[int] = None _inst: Dict[type, Any] = {} objs: Dict[str, Any] = {} cache: Cache = Cache() get_resource(res_name: str, t: Optional[Type]=None) -> Any at: ciphey.iface._modules.Checker check(self, text: T) -> Optional[str] __init__(config: Config) __init__(self, config: Config) at: ciphey.iface._modules.ConfigurableModule _params() at: ciphey.mathsHelper mathsHelper()
ciphey.basemods.Checkers.brandon/Brandon.check
Modified
Ciphey~Ciphey
084cc94ff9b3424a03e8cd966e4cb5b6fe5c7424
removing logs
<30>:<del> logger.trace(f"What to use is {what_to_use}") <36>:<del> logger.trace("using trace")
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: <0> """Checks to see if the text is in English <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> text -> The text we use to perform analysis on <6> <7> Returns: <8> bool -> True if the text is English, False otherwise. <9> <10> """ <11> logger.trace(f'In Language Checker with "{text}"') <12> text = self.clean_text(text) <13> logger.trace(f'Text split to "{text}"') <14> if text == "": <15> return None <16> <17> length_text = len(text) <18> <19> # "Phase 1": {0: {"check": 0.02}, 110: {"stop": 0.15}, 150: {"stop": 0.28}} <20> <21> # Phase 1 checking <22> <23> what_to_use = {} <24> <25> # this code decides what checker / threshold to use <26> # if text is over or equal to maximum size, just use the maximum possible checker <27> what_to_use = self.calculateWhatChecker( <28> length_text, self.thresholds_phase1.keys() <29> ) <30> logger.trace(f"What to use is {what_to_use}") <31> logger.trace(self.thresholds_phase1) <32> what_to_use = self.thresholds_phase1[str(what_to_use)] <33> # def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: <34> if "check" in what_to_use: <35> # perform check 1k words <36> logger.trace("using trace") <37> result =</s>
===========below chunk 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: # offset: 1 text, what_to_use["check"], length_text, self.top1000Words ) logger.trace(f"The result from check 1k words is {result}") elif "stop" in what_to_use: # perform stopwords logger.trace("using trace") result = self.checker( text, what_to_use["stop"], length_text, self.stopwords ) logger.trace(f"The result from check stopwords is {result}") elif "dict" in what_to_use: logger.trace("in dict") result = self.checker(text, what_to_use["dict"], length_text, self.wordlist) # If result is None, no point doing it again in phase2 if not result: return None else: logger.debug(f"It is neither stop or check, but instead {what_to_use}") # return False if phase 1 fails if not result: return None else: what_to_use = self.calculateWhatChecker( length_text, self.thresholds_phase2.keys() ) what_to_use = self.thresholds_phase2[str(what_to_use)] result = self.checker(text, what_to_use["dict"], length_text, self.wordlist) logger.trace(f"Result of dictionary checker is {result}") return "" if result else None ===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon wordlist: set clean_text(text: str) -> set checker(text: str, threshold: float, text_length: int, var: set) -> bool at: ciphey.basemods.Checkers.brandon.Brandon.__init__ self.thresholds_phase1 = phases["1"] self.thresholds_phase2 = phases["2"] self.top1000Words = config.get_resource(self._params().get("top1000")) self.wordlist = config.get_resource(self._params()["wordlist"]) self.stopwords = config.get_resource(self._params().get("stopwords")) ===========changed ref 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def __init__(self, config: ciphey.iface.Config): # Suppresses warning super().__init__(config) self.mh = mh.mathsHelper() phases = config.get_resource(self._params()["phases"]) - print(phases) self.thresholds_phase1 = phases["1"] - print(self.thresholds_phase1) self.thresholds_phase2 = phases["2"] - print(self.thresholds_phase2) self.top1000Words = config.get_resource(self._params().get("top1000")) self.wordlist = config.get_resource(self._params()["wordlist"]) self.stopwords = config.get_resource(self._params().get("stopwords")) self.len_phase1 = len(self.thresholds_phase1) self.len_phase2 = len(self.thresholds_phase2)
ciphey.basemods.Checkers.brandon/Brandon.calculateWhatChecker
Modified
Ciphey~Ciphey
084cc94ff9b3424a03e8cd966e4cb5b6fe5c7424
removing logs
<19>:<del> logger.trace( <20>:<del> f"Length of text is max therefore what to use is {what_to_use}" <21>:<del> ) <24>:<del> logger.trace(f"{_keys}") <26>:<del> logger.trace(f"counter -1 is {_keys[counter -1]}") <27>:<del> logger.trace(f"{length_text} <= {i}")
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def calculateWhatChecker(self, length_text, key): <0> """Calculates what threshold / checker to use <1> <2> If the length of the text is over the maximum sentence length, use the last checker / threshold <3> Otherwise, traverse the keys backwards until we find a key range that does not fit. <4> So we traverse backwards and see if the sentence length is between current - 1 and current <5> In this way, we find the absolute lowest checker / percentage threshold. <6> We traverse backwards because if the text is longer than the max sentence length, we already know. <7> In total, the keys are only 5 items long or so. It is not expensive to move backwards, nor is it expensive to move forwards. <8> <9> Args: <10> length_text -> The length of the text <11> key -> What key we want to use. I.E. Phase1 keys, Phase2 keys. <12> Returns: <13> what_to_use -> the key of the lowest checker.""" <14> <15> _keys = list(key) <16> _keys = list(map(int, _keys)) <17> if length_text >= int(_keys[-1]): <18> what_to_use = key[_keys[-1]] <19> logger.trace( <20> f"Length of text is max therefore what to use is {what_to_use}" <21> ) <22> else: <23> # this algorithm finds the smallest possible fit for the text <24> logger.trace(f"{_keys}") <25> for counter, i in reversed(list(enumerate(_keys))): <26> logger.trace(f"counter -1 is {_keys[counter -1]}") <27> logger.trace(f"{length_text} <= {i}") <28> # [0, 110, 150] <29> if i <= length_text: <30> what_to_use =</s>
===========below chunk 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def calculateWhatChecker(self, length_text, key): # offset: 1 logger.trace(f"{length_text} <= {i}") logger.trace(f"else what to use is {what_to_use}") return what_to_use ===========unchanged ref 0=========== at: ciphey.iface._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.ConfigurableModule getParams() -> Optional[Dict[str, ParamSpec]] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def __init__(self, config: ciphey.iface.Config): # Suppresses warning super().__init__(config) self.mh = mh.mathsHelper() phases = config.get_resource(self._params()["phases"]) - print(phases) self.thresholds_phase1 = phases["1"] - print(self.thresholds_phase1) self.thresholds_phase2 = phases["2"] - print(self.thresholds_phase2) self.top1000Words = config.get_resource(self._params().get("top1000")) self.wordlist = config.get_resource(self._params()["wordlist"]) self.stopwords = config.get_resource(self._params().get("stopwords")) self.len_phase1 = len(self.thresholds_phase1) self.len_phase2 = len(self.thresholds_phase2) ===========changed ref 1=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: """Checks to see if the text is in English Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: text -> The text we use to perform analysis on Returns: bool -> True if the text is English, False otherwise. """ logger.trace(f'In Language Checker with "{text}"') text = self.clean_text(text) logger.trace(f'Text split to "{text}"') if text == "": return None length_text = len(text) # "Phase 1": {0: {"check": 0.02}, 110: {"stop": 0.15}, 150: {"stop": 0.28}} # Phase 1 checking what_to_use = {} # this code decides what checker / threshold to use # if text is over or equal to maximum size, just use the maximum possible checker what_to_use = self.calculateWhatChecker( length_text, self.thresholds_phase1.keys() ) - logger.trace(f"What to use is {what_to_use}") logger.trace(self.thresholds_phase1) what_to_use = self.thresholds_phase1[str(what_to_use)] # def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: if "check" in what_to_use: # perform check 1k words - logger.trace("using trace") result = self.checker( text, what_to_use["check"], length_text, self.top1000Words ) - logger</s> ===========changed ref 2=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def check(self, text: str) -> Optional[str]: # offset: 1 <s> text, what_to_use["check"], length_text, self.top1000Words ) - logger.trace(f"The result from check 1k words is {result}") elif "stop" in what_to_use: # perform stopwords - logger.trace("using trace") result = self.checker( text, what_to_use["stop"], length_text, self.stopwords ) - logger.trace(f"The result from check stopwords is {result}") elif "dict" in what_to_use: - logger.trace("in dict") result = self.checker(text, what_to_use["dict"], length_text, self.wordlist) # If result is None, no point doing it again in phase2 if not result: return None else: logger.debug(f"It is neither stop or check, but instead {what_to_use}") # return False if phase 1 fails if not result: return None else: what_to_use = self.calculateWhatChecker( length_text, self.thresholds_phase2.keys() ) what_to_use = self.thresholds_phase2[str(what_to_use)] result = self.checker(text, what_to_use["dict"], length_text, self.wordlist) - logger.trace(f"Result of dictionary checker is {result}") return "" if result else None
ciphey.basemods.Crackers.vigenere/Vigenere.crackOne
Modified
Ciphey~Ciphey
e65191d4a32885bb60141d5bbedc4491a0f78c8f
Merge pull request #177 from Ciphey/cleaningRoot
<3>:<add> logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") <8>:<add> for candidate in possible_keys[:min(len(possible_keys), 10)] <del> for candidate in possible_keys
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: <0> possible_keys = cipheycore.vigenere_crack( <1> analysis, self.expected, self.group, self.p_value <2> ) <3> return [ <4> CrackResult( <5> value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), <6> key_info="".join([self.group[i] for i in candidate.key]), <7> ) <8> for candidate in possible_keys <9> ] <10>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.p_value = self._params()["p_value"] at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: typing List = _alias(list, 1, inst=False, name='List')
ciphey.basemods.Crackers.vigenere/Vigenere.__init__
Modified
Ciphey~Ciphey
e65191d4a32885bb60141d5bbedc4491a0f78c8f
Merge pull request #177 from Ciphey/cleaningRoot
<10>:<del> self.MAX_KEY_LENGTH = 16 # Will not attempt keys longer than this. <12>:<add> self.MAX_KEY_LENGTH = 16
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def __init__(self, config: ciphey.iface.Config): <0> super().__init__(config) <1> self.lower: Union[str, bool] = self._params()["lower"] <2> if type(self.lower) != bool: <3> self.lower = util.strtobool(self.lower) <4> self.group = list(self._params()["group"]) <5> self.expected = config.get_resource(self._params()["expected"]) <6> self.cache = config.cache <7> self.keysize = self._params().get("keysize") <8> if self.keysize is not None: <9> self.keysize = int(self.keysize) <10> self.MAX_KEY_LENGTH = 16 # Will not attempt keys longer than this. <11> self.p_value = self._params()["p_value"] <12>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._config.Config verbosity: int = 0 searcher: str = "perfection" params: Dict[str, Dict[str, Union[str, List[str]]]] = {} format: Dict[str, str] = {"in": "str", "out": "str"} modules: List[str] = [] checker: str = "brandon" default_dist: str = "cipheydists::dist::twist" timeout: Optional[int] = None _inst: Dict[type, Any] = {} objs: Dict[str, Any] = {} cache: Cache = Cache() get_resource(res_name: str, t: Optional[Type]=None) -> Any at: ciphey.iface._modules.ConfigurableModule _params() at: ciphey.iface._modules.Cracker __init__(config: Config) __init__(self, config: Config) at: distutils.util strtobool(val: str) -> bool ===========changed ref 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) + logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") return [ CrackResult( value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), key_info="".join([self.group[i] for i in candidate.key]), ) + for candidate in possible_keys[:min(len(possible_keys), 10)] - for candidate in possible_keys ]
ciphey.ciphey/get_name
Modified
Ciphey~Ciphey
a969de92e9096a36b1c9cbc1b511b5198ea45712
Added nice config method
<7>:<del> return locals() <8>:<del>
# module: ciphey.ciphey def get_name(ctx, param, value): <0> # reads from stdin if the argument wasnt supplied <1> if not value and not click.get_text_stream("stdin").isatty(): <2> click.get_text_stream("stdin").read().strip() <3> return click.get_text_stream("stdin").read().strip() <4> else: <5> return value <6> <7> return locals() <8>
===========unchanged ref 0=========== at: click.utils get_text_stream(name: str, encoding: Optional[str]=..., errors: str=...) -> IO[str] at: typing.IO __slots__ = () isatty() -> bool read(n: int=...) -> AnyStr ===========changed ref 0=========== # module: ciphey.iface._config class Config: + # Does all the loading and filling + + def complete_config(self): + self.load_modules() + self.load_objs() + self.update_log_level(self.verbosity) +
ciphey.ciphey/main
Modified
Ciphey~Ciphey
a969de92e9096a36b1c9cbc1b511b5198ea45712
Added nice config method
<s> help="Adds a module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is not None: <32> dirs = AppDirs("Ciphey", "Ciphey") <33> </s>
===========below chunk 0=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) else: config.load_file(cfg_arg) # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) config.load_modules() # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") output_format = kwargs["bytes_output"] if kwargs["bytes_output"] is not None: config.update_format("</s> ===========below chunk 1=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s>_format = kwargs["bytes_output"] if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.load_objs() logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run c</s> ===========below chunk 2=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction ===========unchanged ref 1=========== option(*param_decls: str, cls: Type[Option]=..., show_default: Union[bool, Text]=..., prompt: Union[bool, Text]=..., confirmation_prompt: bool=..., hide_input: bool=..., is_flag: Optional[bool]=..., flag_value: Optional[Any]=..., multiple: bool=..., count: bool=..., allow_from_autoenv: bool=..., type: _T=..., help: Optional[str]=..., show_choices: bool=..., default: Optional[Any]=..., required: bool=..., callback: Optional[Callable[[Context, Union[Option, Parameter], Union[bool, int, str]], _T]]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., **kwargs: Any) -> _IdentityFunction option(*param_decls: str, cls: Type[Option]=..., show_default: Union[bool, Text]=..., prompt: Union[bool, Text]=..., confirmation_prompt: bool=..., hide_input: bool=..., is_flag: Optional[bool]=..., flag_value: Optional[Any]=..., multiple: bool=..., count: bool=..., allow_from_autoenv: bool=..., type: Type[int]=..., help: Optional[str]=..., show_choices: bool=..., default: Optional[Any]=..., required: bool=..., callback: Callable[[Context, Union[Option, Parameter], int], Any]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., **kwargs: Any) -> _IdentityFunction option(*param_decls: Text, cls: Type[Option]=..., show_default: Union[bool, Text]=..., prompt: Union[bool, Text]=..., confirmation_prompt: bool=...,</s>
ciphey.ciphey/main
Modified
Ciphey~Ciphey
b9a48e73323689fc08f8fd3957c354da1adae478
Added latent debugging for log file loading
<s> help="Adds a module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is not None: <32> dirs = AppDirs("Ciphey", "Ciphey") <33> </s>
===========below chunk 0=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) else: config.load_file(cfg_arg) # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["</s> ===========below chunk 1=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s> None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --</s> ===========below chunk 2=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.ciphey/main
Modified
Ciphey~Ciphey
e0f887571c8c608e637ba7992a68d237ca3ce568
whoops
<s> help="Adds a module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is not None: <32> dirs = AppDirs("Ciphey", "Ciphey") <33> </s>
===========below chunk 0=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir.__func__(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats</s> ===========below chunk 1=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s> if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error.</s> ===========below chunk 2=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.ciphey/main
Modified
Ciphey~Ciphey
c25c1e3301a768c5f88a0d5114b8d69789349129
whoops II: in space, no-one can hear you force push
<s> help="Adds a module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is not None: <32> dirs = AppDirs("Ciphey", "Ciphey") <33> </s>
===========below chunk 0=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate</s> ===========below chunk 1=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s>_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were</s> ===========below chunk 2=========== <s> module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.ciphey/main
Modified
Ciphey~Ciphey
9c83057f475fe2a6882758140a1ade116d165a87
Merge pull request #181 from Ciphey/fixingCI
<33>:<add> path_to_config = dirs.user_config_dir <add> import os <add> print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") <del> ((bad delete))
<s> path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, + is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is not None: <32> dirs = AppDirs("Ciphey", "Ciphey") <33> </s>
===========below chunk 0=========== <s>=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, + is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate</s> ===========below chunk 1=========== <s>=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, + is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s>_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were</s> ===========below chunk 2=========== <s>=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, + is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.ciphey/main
Modified
Ciphey~Ciphey
dd2e98c03b214ec0f791e30d4b083040a8ce69e6
Merge branch 'master' of github.com:Ciphey/Ciphey
<31>:<add> if kwargs["appdirs"] is True: <del> if kwargs["appdirs"] is not None:
<s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is not None: <32> dirs = AppDirs("Ciphey", "Ciphey") <33> </s>
===========below chunk 0=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 import os print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg =</s> ===========below chunk 1=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s> logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None</s> ===========below chunk 2=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.ciphey/main
Modified
Ciphey~Ciphey
09e6bda56738e7b149dea05f89af48332d272e4c
Removed useless imports in Ciphey.py, fixing CI
<31>:<add> if "appdirs" in kwargs and kwargs["appdirs"]: <del> if kwargs["appdirs"] is True:
<s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if kwargs["appdirs"] is True: <32> dirs = AppDirs("Ciphey", "Ciphey") <33> </s>
===========below chunk 0=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 import os print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg =</s> ===========below chunk 1=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s> logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None</s> ===========below chunk 2=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result
tests.test_main/test_initial
Modified
Ciphey~Ciphey
09e6bda56738e7b149dea05f89af48332d272e4c
Removed useless imports in Ciphey.py, fixing CI
<12>:<add> print(result.output)
# module: tests.test_main def test_initial(): <0> runner = CliRunner() <1> # result = runner.invoke(main, ["hello my name is bee and i like bees"]) <2> result = runner.invoke( <3> main, <4> [ <5> "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", <6> "-vvv", <7> ], <8> ) <9> print(result) <10> print(result.output) <11> assert result.exit_code == 0 <12> assert "dog" in result.output <13>
===========changed ref 0=========== <s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: """Ciphey - Automated Decryption Tool Documentation: https://docs.ciphey.online\n Discord (support here, we're online most of the day): https://discord.ciphey.online/\n GitHub: https://github.com/ciphey/ciphey\n Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. Examples:\n Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" """ """Function to deal with arguments. Either calls with args or not. Makes Pytest work. It gets the arguments in the function definition using locals() if withArgs is True, that means this is being called with command line args so go to arg_parsing() to get those args we then update locals() with the new command line args and remove "withArgs" This function then calls call_encryption(**result) which passes our dict of args to the function as its own arguments using dict unpacking. Returns: The output of the decryption. """ # if user wants to know where appdirs is # print and exit + if "appdirs" in kwargs and kwargs["appdirs"]: - if kwargs["appdirs"] is True: dirs = AppDirs("Ciphey", "Ciphey") path_to_config = dirs.user_config_dir - </s> ===========changed ref 1=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 <s> AppDirs("Ciphey", "Ciphey") path_to_config = dirs.user_config_dir - import os print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base </s> ===========changed ref 2=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s>.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["</s> ===========changed ref 3=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result
tests.test_main/test_initial
Modified
Ciphey~Ciphey
842a3b4f65deb6fce4dd2233de23d56dd6d87f07
trying CI
<6>:<add> "-q", <del> "-vvv",
# module: tests.test_main def test_initial(): <0> runner = CliRunner() <1> # result = runner.invoke(main, ["hello my name is bee and i like bees"]) <2> result = runner.invoke( <3> main, <4> [ <5> "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", <6> "-vvv", <7> ], <8> ) <9> print(result) <10> print(result.output) <11> assert result.exit_code == 0 <12> print(result.output) <13> assert "dog" in result.output <14>
tests.test_main/test_base16
Modified
Ciphey~Ciphey
842a3b4f65deb6fce4dd2233de23d56dd6d87f07
trying CI
<6>:<add> "-q", <del> "-vvv", <7>:<add> ] <del> ],
# module: tests.test_main def test_base16(): <0> runner = CliRunner() <1> # result = runner.invoke(main, ["hello my name is bee and i like bees"]) <2> result = runner.invoke( <3> main, <4> [ <5> "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", <6> "-vvv", <7> ], <8> ) <9> assert result.exit_code == 0 <10> assert "dog" in result.output <11>
===========changed ref 0=========== # module: tests.test_main def test_initial(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", + "-q", - "-vvv", ], ) print(result) print(result.output) assert result.exit_code == 0 print(result.output) assert "dog" in result.output
tests.test_main/test_caesar
Modified
Ciphey~Ciphey
842a3b4f65deb6fce4dd2233de23d56dd6d87f07
trying CI
<2>:<add> main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], <del> main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-vvv"],
# module: tests.test_main def test_caesar(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-vvv"], <3> ) <4> assert result.exit_code == 0 <5> assert "dog" in result.output <6>
===========changed ref 0=========== # module: tests.test_main def test_base16(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", + "-q", - "-vvv", + ] - ], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 1=========== # module: tests.test_main def test_initial(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", + "-q", - "-vvv", ], ) print(result) print(result.output) assert result.exit_code == 0 print(result.output) assert "dog" in result.output
tests.test_main/test_base64_caesar
Modified
Ciphey~Ciphey
842a3b4f65deb6fce4dd2233de23d56dd6d87f07
trying CI
<5>:<add> "-q", <del> "-vvv",
# module: tests.test_main def test_base64_caesar(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, <3> [ <4> "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100 01011000 01010001 01100111 01010011 01010011 01000010 01101000 01100010 01001000 01001110 01110110 01001001 01000111 01010010 01110110 01001001 01000111 01101000 01101000 01100011 01001000 01000010 01101100 01100010 01101001 01000010 00110000 01100010 01111001 01000010 01101100 01100010 01101101 01110000 01110110 01100101 01010011 01000010 00110011 01011001 01010111 01111000 01110010 01100011 01110111 00111101 00111101", <5> "-vvv", <6> ], <7> ) <8> assert result.exit_code == 0 <9> assert "dog" in result.output <10>
===========changed ref 0=========== # module: tests.test_main def test_caesar(): runner = CliRunner() result = runner.invoke( + main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], - main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-vvv"], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 1=========== # module: tests.test_main def test_base16(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", + "-q", - "-vvv", + ] - ], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 2=========== # module: tests.test_main def test_initial(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", + "-q", - "-vvv", ], ) print(result) print(result.output) assert result.exit_code == 0 print(result.output) assert "dog" in result.output
tests.test_main/test_vigenere
Modified
Ciphey~Ciphey
842a3b4f65deb6fce4dd2233de23d56dd6d87f07
trying CI
<2>:<add> main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-q"], <del> main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-vvv"],
# module: tests.test_main def test_vigenere(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-vvv"], <3> ) <4> assert result.exit_code == 0 <5> assert "dog" in result.output <6>
===========changed ref 0=========== # module: tests.test_main def test_caesar(): runner = CliRunner() result = runner.invoke( + main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], - main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-vvv"], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 1=========== # module: tests.test_main def test_base16(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", + "-q", - "-vvv", + ] - ], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 2=========== # module: tests.test_main def test_initial(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", + "-q", - "-vvv", ], ) print(result) print(result.output) assert result.exit_code == 0 print(result.output) assert "dog" in result.output ===========changed ref 3=========== # module: tests.test_main def test_base64_caesar(): runner = CliRunner() result = runner.invoke( main, [ "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100 01011000 01010001 01100111 01010011 01010011 01000010 01101000 01100010 01001000 01001110 01110110 01001001 01000111 01010010 01110110 01001001 01000111 01101000 01101000 01100011 01001000 01000010 01101100 01100010 01101001 01000010 00110000 01100010 01111001 01000010 01101100 01100010 01101101 01110000 01110110 01100101 01010011 01000010 00110011 01011001 01010111 01111000 01110010 01100011 01110111 00111101 00111101", + "-q", - "-vvv", ], ) assert result.exit_code == 0 assert "dog" in result.output
tests.test_main/test_binary
Modified
Ciphey~Ciphey
842a3b4f65deb6fce4dd2233de23d56dd6d87f07
trying CI
<5>:<add> "-q", <del> "-vvv",
# module: tests.test_main def test_binary(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, <3> [ <4> "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100", <5> "-vvv", <6> ], <7> ) <8> assert result.exit_code == 0 <9> assert "dog" in result.output <10>
===========changed ref 0=========== # module: tests.test_main def test_vigenere(): runner = CliRunner() result = runner.invoke( + main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-q"], - main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-vvv"], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 1=========== # module: tests.test_main def test_caesar(): runner = CliRunner() result = runner.invoke( + main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], - main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-vvv"], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 2=========== # module: tests.test_main def test_base16(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", + "-q", - "-vvv", + ] - ], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 3=========== # module: tests.test_main def test_initial(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", + "-q", - "-vvv", ], ) print(result) print(result.output) assert result.exit_code == 0 print(result.output) assert "dog" in result.output ===========changed ref 4=========== # module: tests.test_main def test_base64_caesar(): runner = CliRunner() result = runner.invoke( main, [ "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100 01011000 01010001 01100111 01010011 01010011 01000010 01101000 01100010 01001000 01001110 01110110 01001001 01000111 01010010 01110110 01001001 01000111 01101000 01101000 01100011 01001000 01000010 01101100 01100010 01101001 01000010 00110000 01100010 01111001 01000010 01101100 01100010 01101101 01110000 01110110 01100101 01010011 01000010 00110011 01011001 01010111 01111000 01110010 01100011 01110111 00111101 00111101", + "-q", - "-vvv", ], ) assert result.exit_code == 0 assert "dog" in result.output
tests.test_main/test_hex
Modified
Ciphey~Ciphey
842a3b4f65deb6fce4dd2233de23d56dd6d87f07
trying CI
<5>:<add> "-q", <del> "-vvv",
# module: tests.test_main def test_hex(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, <3> [ <4> "48 65 6c 6c 6f 20 6d 79 20 6e 61 6d 65 20 69 73 20 62 65 65 20 61 6e 64 20 49 20 6c 69 6b 65 20 64 6f 67 20 61 6e 64 20 63 61 74", <5> "-vvv", <6> ], <7> ) <8> assert result.exit_code == 0 <9> assert "dog" in result.output <10>
===========changed ref 0=========== # module: tests.test_main def test_vigenere(): runner = CliRunner() result = runner.invoke( + main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-q"], - main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-vvv"], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 1=========== # module: tests.test_main def test_caesar(): runner = CliRunner() result = runner.invoke( + main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], - main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-vvv"], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 2=========== # module: tests.test_main def test_base16(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", + "-q", - "-vvv", + ] - ], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 3=========== # module: tests.test_main def test_initial(): runner = CliRunner() # result = runner.invoke(main, ["hello my name is bee and i like bees"]) result = runner.invoke( main, [ "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", + "-q", - "-vvv", ], ) print(result) print(result.output) assert result.exit_code == 0 print(result.output) assert "dog" in result.output ===========changed ref 4=========== # module: tests.test_main def test_binary(): runner = CliRunner() result = runner.invoke( main, [ "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100", + "-q", - "-vvv", ], ) assert result.exit_code == 0 assert "dog" in result.output ===========changed ref 5=========== # module: tests.test_main def test_base64_caesar(): runner = CliRunner() result = runner.invoke( main, [ "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100 01011000 01010001 01100111 01010011 01010011 01000010 01101000 01100010 01001000 01001110 01110110 01001001 01000111 01010010 01110110 01001001 01000111 01101000 01101000 01100011 01001000 01000010 01101100 01100010 01101001 01000010 00110000 01100010 01111001 01000010 01101100 01100010 01101101 01110000 01110110 01100101 01010011 01000010 00110011 01011001 01010111 01111000 01110010 01100011 01110111 00111101 00111101", + "-q", - "-vvv", ], ) assert result.exit_code == 0 assert "dog" in result.output
ciphey.basemods.Checkers.brandon/Brandon.checker
Modified
Ciphey~Ciphey
0fbe29ee45c1393ab805a447c5319090693ca2ff
removed 2 letter words from dictionary#
<31>:<add> if word in var and len(word) > 2: <del> if word in var:
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: <0> """Given text determine if it passes checker <1> <2> The checker uses the vairable passed to it. I.E. Stopwords list, 1k words, dictionary <3> <4> Args: <5> text -> The text to check <6> threshold -> at what point do we return True? The percentage of text that is in var before we return True <7> text_length -> the length of the text <8> var -> the variable we are checking against. Stopwords list, 1k words list, dictionray list. <9> Returns: <10> boolean -> True for it passes the test, False for it fails the test.""" <11> if text is None: <12> logger.trace(f"Checker's text is None, so returning False") <13> return False <14> if var is None: <15> logger.trace(f"Checker's input var is None, so returning False") <16> return False <17> <18> percent = ceil(text_length * threshold) <19> logger.trace(f"Checker's chunks are size {percent}") <20> meet_threshold = 0 <21> location = 0 <22> end = percent <23> <24> while location <= text_length: <25> # chunks the text, so only gets THRESHOLD chunks of text at a time <26> text = list(text) <27> to_analyse = text[location:end] <28> logger.trace(f"To analyse is {to_analyse}") <29> for word in to_analyse: <30> # if word is a stopword, + 1 to the counter <31> if word in var: <32> logger.trace( <33> f"{word} is in var, which means I am +=1 to the meet_threshold which is {me</s>
===========below chunk 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: # offset: 1 ) meet_threshold += 1 meet_threshold_percent = meet_threshold / text_length if meet_threshold_percent >= threshold: logger.trace( f"Returning true since the percentage is {meet_threshold / text_length} and the threshold is {threshold}" ) # if we meet the threshold, return True # otherwise, go over again until we do # We do this in the for loop because if we're at 24% and THRESHOLD is 25 # we don't want to wait THRESHOLD to return true, we want to return True ASAP return True location = end end = end + percent logger.trace( f"The language proportion {meet_threshold_percent} is under the threshold {threshold}" ) return False ===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon wordlist: set at: math ceil(x: SupportsFloat, /) -> int
ciphey.iface._registry/Registry.register
Modified
Ciphey~Ciphey
f1d6053ef2970a5251aebb9b2157ece997a55bb2
fixed register decorator causing classes to be NoneType
<0>:<add> return self._real_register(input_type) <del> self._real_register(input_type)
# module: ciphey.iface._registry class Registry: def register(self, input_type): <0> self._real_register(input_type) <1>
===========unchanged ref 0=========== at: ciphey.iface._registry.Registry RegElem = Union[List[Type], Dict[Type, "RegElem"]] _reg: Dict[Type, RegElem] = {} _names: Dict[str, Tuple[Type, Set[Type]]] = {} _targets: Dict[str, Dict[Type, List[Type]]] = {} _modules = {Checker, Cracker, Decoder, ResourceLoader, Searcher} _real_register(input_type: type, *args) -> Type
ciphey.basemods.Checkers.ezcheck/EzCheck.check
Modified
Ciphey~Ciphey
154a3af6e0192d5b74408e47c80b34cdb30782ff
ezcheck looks good
<0>:<add> for checker in self.checkers: <add> res = checker.check(text) <add> if res is not None: <add> return res <add> return None <del> pass
# module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): def check(self, text: T) -> Optional[str]: <0> pass <1>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") at: ciphey.iface._modules.Checker check(self, text: T) -> Optional[str] ===========changed ref 0=========== + # module: ciphey.basemods.Checkers.format + + ===========changed ref 1=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + pass + ===========changed ref 2=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 3=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + """ + This object is effectively a prebuilt quroum (with requirement 1) of common patterns + """ + ===========changed ref 4=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + def getExpectedRuntime(self, text: T) -> float: + # TODO: actually bench this + return 1e-7 * len(text) # From benchmarks I found online + ===========changed ref 5=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + def check(self, text: T) -> Optional[str]: + logger.trace(f"Trying json checker") + + try: + json.loads(text) + return "" + except ValueError: + return None +
ciphey.basemods.Checkers.ezcheck/EzCheck.__init__
Modified
Ciphey~Ciphey
154a3af6e0192d5b74408e47c80b34cdb30782ff
ezcheck looks good
<10>:<add> # Next, the json checker <del> # Then the brandon checker <11>:<add> self.checkers.append(config(JsonChecker)) <add> <add> # Finally, the Brandon checker, as it is the slowest
# module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): def __init__(self, config: Config): <0> super().__init__(config) <1> <2> # We need to modify the config for each of the objects <3> <4> # First the flag regexes, as they are the fastest <5> flags_config = config <6> flags_config.update_param("regexlist", "resource", "cipheydists::list::flags") <7> # We do not cache, as this uses a different, on-time config <8> self.checkers.append(RegexList(flags_config)) <9> <10> # Then the brandon checker <11> self.checkers.append(config(Brandon)) <12>
===========unchanged ref 0=========== at: ciphey.basemods.Checkers.ezcheck.EzCheck checkers: List[Checker[str]] = [] at: ciphey.iface._config Config() at: ciphey.iface._config.Config verbosity: int = 0 searcher: str = "perfection" params: Dict[str, Dict[str, Union[str, List[str]]]] = {} format: Dict[str, str] = {"in": "str", "out": "str"} modules: List[str] = [] checker: str = "ezcheck" default_dist: str = "cipheydists::dist::twist" timeout: Optional[int] = None _inst: Dict[type, Any] = {} objs: Dict[str, Any] = {} cache: Cache = Cache() update_param(owner: str, name: str, value: Optional[Any]) at: ciphey.iface._modules T = TypeVar("T") at: ciphey.iface._modules.Checker getExpectedRuntime(self, text: T) -> float getExpectedRuntime(text: T) -> float __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): def check(self, text: T) -> Optional[str]: + for checker in self.checkers: + res = checker.check(text) + if res is not None: + return res + return None - pass ===========changed ref 1=========== + # module: ciphey.basemods.Checkers.format + + ===========changed ref 2=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + pass + ===========changed ref 3=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 4=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + """ + This object is effectively a prebuilt quroum (with requirement 1) of common patterns + """ + ===========changed ref 5=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + def getExpectedRuntime(self, text: T) -> float: + # TODO: actually bench this + return 1e-7 * len(text) # From benchmarks I found online + ===========changed ref 6=========== + # module: ciphey.basemods.Checkers.format + @registry.register + class JsonChecker(Checker[str]): + def check(self, text: T) -> Optional[str]: + logger.trace(f"Trying json checker") + + try: + json.loads(text) + return "" + except ValueError: + return None +
ciphey.basemods.Checkers.brandon/Brandon.clean_text
Modified
Ciphey~Ciphey
5e67c34274ac8ad9700aa616b0ec5a4b0c629129
analysis only performed in text more than 2 chars
<15>:<add> text = filter(lambda x: len(x) > 2, text)
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def clean_text(self, text: str) -> set: <0> """Cleans the text ready to be checked <1> <2> Strips punctuation, makes it lower case, turns it into a set separated by spaces, removes duplicate words <3> <4> Args: <5> text -> The text we use to perform analysis on <6> <7> Returns: <8> text -> the text as a list, now cleaned <9> <10> """ <11> # makes the text unique words and readable <12> text = text.lower() <13> text = self.mh.strip_puncuation(text) <14> text = text.split(" ") <15> text = set(text) <16> return text <17> <18> x = [] <19> for word in text: <20> # poor mans lemisation <21> # removes 's from the dict' <22> if word.endswith("'s"): <23> x.append(word[0:-2]) <24> text = self.mh.strip_puncuation(x) <25> # turns it all into lowercase and as a set <26> complete = set([word.lower() for word in x]) <27> <28> return complete <29>
===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon wordlist: set at: ciphey.basemods.Checkers.brandon.Brandon.__init__ self.mh = mh.mathsHelper() at: mathsHelper.mathsHelper strip_puncuation(text: str) -> str
ciphey.basemods.Checkers.brandon/Brandon.checker
Modified
Ciphey~Ciphey
5e67c34274ac8ad9700aa616b0ec5a4b0c629129
analysis only performed in text more than 2 chars
<31>:<add> if word in var: <del> if word in var and len(word) > 2:
# module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: <0> """Given text determine if it passes checker <1> <2> The checker uses the vairable passed to it. I.E. Stopwords list, 1k words, dictionary <3> <4> Args: <5> text -> The text to check <6> threshold -> at what point do we return True? The percentage of text that is in var before we return True <7> text_length -> the length of the text <8> var -> the variable we are checking against. Stopwords list, 1k words list, dictionray list. <9> Returns: <10> boolean -> True for it passes the test, False for it fails the test.""" <11> if text is None: <12> logger.trace(f"Checker's text is None, so returning False") <13> return False <14> if var is None: <15> logger.trace(f"Checker's input var is None, so returning False") <16> return False <17> <18> percent = ceil(text_length * threshold) <19> logger.trace(f"Checker's chunks are size {percent}") <20> meet_threshold = 0 <21> location = 0 <22> end = percent <23> <24> while location <= text_length: <25> # chunks the text, so only gets THRESHOLD chunks of text at a time <26> text = list(text) <27> to_analyse = text[location:end] <28> logger.trace(f"To analyse is {to_analyse}") <29> for word in to_analyse: <30> # if word is a stopword, + 1 to the counter <31> if word in var and len(word) > 2: <32> logger.trace( <33> f"{word} is in var, which means I am +=1 to the</s>
===========below chunk 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: # offset: 1 ) meet_threshold += 1 meet_threshold_percent = meet_threshold / text_length if meet_threshold_percent >= threshold: logger.trace( f"Returning true since the percentage is {meet_threshold / text_length} and the threshold is {threshold}" ) # if we meet the threshold, return True # otherwise, go over again until we do # We do this in the for loop because if we're at 24% and THRESHOLD is 25 # we don't want to wait THRESHOLD to return true, we want to return True ASAP return True location = end end = end + percent logger.trace( f"The language proportion {meet_threshold_percent} is under the threshold {threshold}" ) return False ===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon.clean_text complete = set([word.lower() for word in x]) at: math ceil(x: SupportsFloat, /) -> int ===========changed ref 0=========== # module: ciphey.basemods.Checkers.brandon @registry.register class Brandon(ciphey.iface.Checker[str]): def clean_text(self, text: str) -> set: """Cleans the text ready to be checked Strips punctuation, makes it lower case, turns it into a set separated by spaces, removes duplicate words Args: text -> The text we use to perform analysis on Returns: text -> the text as a list, now cleaned """ # makes the text unique words and readable text = text.lower() text = self.mh.strip_puncuation(text) text = text.split(" ") + text = filter(lambda x: len(x) > 2, text) text = set(text) return text x = [] for word in text: # poor mans lemisation # removes 's from the dict' if word.endswith("'s"): x.append(word[0:-2]) text = self.mh.strip_puncuation(x) # turns it all into lowercase and as a set complete = set([word.lower() for word in x]) return complete
ciphey.ciphey/main
Modified
Ciphey~Ciphey
a569848a704bef46b7bedb5de6206870aca7f216
removed earth from ciphey
<s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if "appdirs" in kwargs and kwargs["appdirs"]: <32> dirs = AppDirs("Ciphey", "Ciph</s>
===========below chunk 0=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") #</s> ===========below chunk 1=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s>) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") </s> ===========below chunk 2=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, text="Earth") as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.iface._modules/pretty_search_results
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<25>:<add> # Skip the 'input' and print in order <del> # Skip the 'input' and print in reverse order <26>:<add> for i in res.path[1:]: <del> for i in res.path[1:][::-1]: <30>:<del> ret += ( <31>:<del> f"""Final result: [bold green]"{res.path[-1].result.value}"[\bold green]\n'""" <32>:<del> ) <33>:<add> ret = ret[:-1] <del> return ret[:-1]
# module: ciphey.iface._modules + def pretty_search_results(res: SearchResult, display_intermediate: bool = False) -> str: - def pretty_search_results(res: SearchResult, display_intermediate: bool = False): <0> ret: str = "" <1> if len(res.check_res) != 0: <2> ret += f"Checker: {res.check_res}\n" <3> ret += "Format used:\n" <4> <5> def add_one(): <6> nonlocal ret <7> ret += f" {i.name}" <8> already_broken = False <9> if i.result.key_info is not None: <10> ret += f":\n Key: {i.result.key_info}\n" <11> already_broken = True <12> if i.result.misc_info is not None: <13> if not already_broken: <14> ret += ":\n" <15> ret += f" Misc: {i.result.misc_info}\n" <16> already_broken = True <17> if display_intermediate: <18> if not already_broken: <19> ret += ":\n" <20> ret += f' Value: "{i.result.value}"\n' <21> already_broken = True <22> if not already_broken: <23> ret += "\n" <24> <25> # Skip the 'input' and print in reverse order <26> for i in res.path[1:][::-1]: <27> add_one() <28> <29> # Remove trailing newline <30> ret += ( <31> f"""Final result: [bold green]"{res.path[-1].result.value}"[\bold green]\n'""" <32> ) <33> return ret[:-1] <34>
===========unchanged ref 0=========== at: ciphey.iface._modules SearchResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.CrackResult value: T key_info: Optional[str] = None misc_info: Optional[str] = None at: ciphey.iface._modules.SearchLevel name: str result: CrackResult at: ciphey.iface._modules.SearchResult path: List[SearchLevel] check_res: str ===========changed ref 0=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 1=========== # module: ciphey.iface._modules class ParamSpec(NamedTuple): """ Attributes: req Whether this argument is required desc A description of what this argument does default The default value for this argument. Ignored if req == True or configPath is not None config_ref The path to the config that should be the default value list Whether this parameter is in the form of a list, and can therefore be specified more than once visible Whether the user can tweak this via the command line """ req: bool desc: str default: Optional[Any] = None list: bool = False config_ref: Optional[List[str]] = None + visible: bool = True - visible: bool = False
ciphey.iface._config/Cache.mark_ctext
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<1>:<add> logger.trace(f"Candidate {ctext.__repr__()} too short!") <del> logger.trace(f"Candidate {ctext} too short!") <5>:<add> logger.trace(f"Deduped {ctext.__repr__()}") <del> logger.trace(f"Deduped {ctext}") <7>:<add> <add> logger.trace(f"New ctext {ctext.__repr__()}")
# module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: <0> if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: <1> logger.trace(f"Candidate {ctext} too short!") <2> return False <3> <4> if ctext in self._cache: <5> logger.trace(f"Deduped {ctext}") <6> return False <7> <8> self._cache[ctext] = {} <9> return True <10>
===========changed ref 0=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 1=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 2=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 3=========== # module: ciphey.iface._modules class ParamSpec(NamedTuple): """ Attributes: req Whether this argument is required desc A description of what this argument does default The default value for this argument. Ignored if req == True or configPath is not None config_ref The path to the config that should be the default value list Whether this parameter is in the form of a list, and can therefore be specified more than once visible Whether the user can tweak this via the command line """ req: bool desc: str default: Optional[Any] = None list: bool = False config_ref: Optional[List[str]] = None + visible: bool = True - visible: bool = False ===========changed ref 4=========== # module: ciphey.iface._modules + def pretty_search_results(res: SearchResult, display_intermediate: bool = False) -> str: - def pretty_search_results(res: SearchResult, display_intermediate: bool = False): ret: str = "" if len(res.check_res) != 0: ret += f"Checker: {res.check_res}\n" ret += "Format used:\n" def add_one(): nonlocal ret ret += f" {i.name}" already_broken = False if i.result.key_info is not None: ret += f":\n Key: {i.result.key_info}\n" already_broken = True if i.result.misc_info is not None: if not already_broken: ret += ":\n" ret += f" Misc: {i.result.misc_info}\n" already_broken = True if display_intermediate: if not already_broken: ret += ":\n" ret += f' Value: "{i.result.value}"\n' already_broken = True if not already_broken: ret += "\n" + # Skip the 'input' and print in order - # Skip the 'input' and print in reverse order + for i in res.path[1:]: - for i in res.path[1:][::-1]: add_one() # Remove trailing newline - ret += ( - f"""Final result: [bold green]"{res.path[-1].result.value}"[\bold green]\n'""" - ) + ret = ret[:-1] - return ret[:-1]
ciphey.iface._config/Config.complete_config
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<add> """This does all the loading for the config, and then returns itself""" <3>:<add> return self
# module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): <0> self.load_modules() <1> self.load_objs() <2> self.update_log_level(self.verbosity) <3>
===========changed ref 0=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 1=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 2=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 3=========== # module: ciphey.iface._config class Config: - verbosity: int = 0 - searcher: str = "perfection" - params: Dict[str, Dict[str, Union[str, List[str]]]] = {} - format: Dict[str, str] = {"in": "str", "out": "str"} - modules: List[str] = [] - checker: str = "ezcheck" - default_dist: str = "cipheydists::dist::twist" - timeout: Optional[int] = None - - _inst: Dict[type, Any] = {} - objs: Dict[str, Any] = {} - cache: Cache = Cache() - ===========changed ref 4=========== # module: ciphey.iface._config class Config: + def __init__(self): + self.verbosity: int = 0 + self.searcher: str = "ausearch" + self.params: Dict[str, Dict[str, Union[str, List[str]]]] = {} + self.format: Dict[str, str] = {"in": "str", "out": "str"} + self.modules: List[str] = [] + self.checker: str = "ezcheck" + self.default_dist: str = "cipheydists::dist::english" + self.timeout: Optional[int] = None + + self._inst: Dict[type, Any] = {} + self.objs: Dict[str, Any] = {} + self.cache: Cache = Cache() + ===========changed ref 5=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: + logger.trace(f"Candidate {ctext.__repr__()} too short!") - logger.trace(f"Candidate {ctext} too short!") return False if ctext in self._cache: + logger.trace(f"Deduped {ctext.__repr__()}") - logger.trace(f"Deduped {ctext}") return False + + logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 6=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 7=========== # module: ciphey.iface._modules class ParamSpec(NamedTuple): """ Attributes: req Whether this argument is required desc A description of what this argument does default The default value for this argument. Ignored if req == True or configPath is not None config_ref The path to the config that should be the default value list Whether this parameter is in the form of a list, and can therefore be specified more than once visible Whether the user can tweak this via the command line """ req: bool desc: str default: Optional[Any] = None list: bool = False config_ref: Optional[List[str]] = None + visible: bool = True - visible: bool = False ===========changed ref 8=========== # module: ciphey.iface._modules + def pretty_search_results(res: SearchResult, display_intermediate: bool = False) -> str: - def pretty_search_results(res: SearchResult, display_intermediate: bool = False): ret: str = "" if len(res.check_res) != 0: ret += f"Checker: {res.check_res}\n" ret += "Format used:\n" def add_one(): nonlocal ret ret += f" {i.name}" already_broken = False if i.result.key_info is not None: ret += f":\n Key: {i.result.key_info}\n" already_broken = True if i.result.misc_info is not None: if not already_broken: ret += ":\n" ret += f" Misc: {i.result.misc_info}\n" already_broken = True if display_intermediate: if not already_broken: ret += ":\n" ret += f' Value: "{i.result.value}"\n' already_broken = True if not already_broken: ret += "\n" + # Skip the 'input' and print in order - # Skip the 'input' and print in reverse order + for i in res.path[1:]: - for i in res.path[1:][::-1]: add_one() # Remove trailing newline - ret += ( - f"""Final result: [bold green]"{res.path[-1].result.value}"[\bold green]\n'""" - ) + ret = ret[:-1] - return ret[:-1]
ciphey.ciphey/decrypt
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<1>:<add> res: Optional[iface.SearchResult] = config.objs["searcher"].search(ctext) <del> res: iface.SearchResult = config.objs["searcher"].search(ctext) <2>:<add> if res is None: <add> return "Failed to crack"
# module: ciphey.ciphey + def decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes]: - def decrypt(config: iface.Config, ctext: Any) -> List[SearchLevel]: <0> """A simple alias for searching a ctext and makes the answer pretty""" <1> res: iface.SearchResult = config.objs["searcher"].search(ctext) <2> if config.verbosity < 0: <3> return res.path[-1].result.value <4> else: <5> return iface.pretty_search_results(res) <6>
===========changed ref 0=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 1=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 2=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 3=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 4=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 5=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 6=========== # module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): + """This does all the loading for the config, and then returns itself""" self.load_modules() self.load_objs() self.update_log_level(self.verbosity) + return self ===========changed ref 7=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: + logger.trace(f"Candidate {ctext.__repr__()} too short!") - logger.trace(f"Candidate {ctext} too short!") return False if ctext in self._cache: + logger.trace(f"Deduped {ctext.__repr__()}") - logger.trace(f"Deduped {ctext}") return False + + logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 8=========== # module: ciphey.iface._config class Config: - verbosity: int = 0 - searcher: str = "perfection" - params: Dict[str, Dict[str, Union[str, List[str]]]] = {} - format: Dict[str, str] = {"in": "str", "out": "str"} - modules: List[str] = [] - checker: str = "ezcheck" - default_dist: str = "cipheydists::dist::twist" - timeout: Optional[int] = None - - _inst: Dict[type, Any] = {} - objs: Dict[str, Any] = {} - cache: Cache = Cache() - ===========changed ref 9=========== # module: ciphey.iface._modules class ParamSpec(NamedTuple): """ Attributes: req Whether this argument is required desc A description of what this argument does default The default value for this argument. Ignored if req == True or configPath is not None config_ref The path to the config that should be the default value list Whether this parameter is in the form of a list, and can therefore be specified more than once visible Whether the user can tweak this via the command line """ req: bool desc: str default: Optional[Any] = None list: bool = False config_ref: Optional[List[str]] = None + visible: bool = True - visible: bool = False ===========changed ref 10=========== # module: ciphey.iface._config class Config: + def __init__(self): + self.verbosity: int = 0 + self.searcher: str = "ausearch" + self.params: Dict[str, Dict[str, Union[str, List[str]]]] = {} + self.format: Dict[str, str] = {"in": "str", "out": "str"} + self.modules: List[str] = [] + self.checker: str = "ezcheck" + self.default_dist: str = "cipheydists::dist::english" + self.timeout: Optional[int] = None + + self._inst: Dict[type, Any] = {} + self.objs: Dict[str, Any] = {} + self.cache: Cache = Cache() + ===========changed ref 11=========== # module: ciphey.iface._modules + def pretty_search_results(res: SearchResult, display_intermediate: bool = False) -> str: - def pretty_search_results(res: SearchResult, display_intermediate: bool = False): ret: str = "" if len(res.check_res) != 0: ret += f"Checker: {res.check_res}\n" ret += "Format used:\n" def add_one(): nonlocal ret ret += f" {i.name}" already_broken = False if i.result.key_info is not None: ret += f":\n Key: {i.result.key_info}\n" already_broken = True if i.result.misc_info is not None: if not already_broken: ret += ":\n" ret += f" Misc: {i.result.misc_info}\n" already_broken = True if display_intermediate: if not already_broken: ret += ":\n" ret += f' Value: "{i.result.value}"\n' already_broken = True if not already_broken: ret += "\n" + # Skip the 'input' and print in order - # Skip the 'input' and print in reverse order + for i in res.path[1:]: - for i in res.path[1:][::-1]: add_one() # Remove trailing newline - ret += ( - f"""Final result: [bold green]"{res.path[-1].result.value}"[\bold green]\n'""" - ) + ret = ret[:-1] - return ret[:-1]
ciphey.ciphey/main
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if "appdirs" in kwargs and kwargs["appdirs"]: <32> dirs = AppDirs("Ciphey", "Ciph</s>
===========below chunk 0=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 1 path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") #</s> ===========below chunk 1=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 2 <s>) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") </s> ===========below chunk 2=========== <s> type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs) -> Optional[dict]: # offset: 3 <s> kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug mode is on, run without spinner try: if config.verbosity > 0: result = decrypt(config, kwargs["text"]) elif config.verbosity == 0: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth) as sp: result = decrypt(config, kwargs["text"]) else: # else its below 0, so quiet mode is on. make it greppable"" result = decrypt(config, kwargs["text"]) except LookupError as e: result = "Could not find any solutions." print(result) return result ===========changed ref 0=========== # module: ciphey.ciphey + def decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes]: - def decrypt(config: iface.Config, ctext: Any) -> List[SearchLevel]: """A simple alias for searching a ctext and makes the answer pretty""" + res: Optional[iface.SearchResult] = config.objs["searcher"].search(ctext) - res: iface.SearchResult = config.objs["searcher"].search(ctext) + if res is None: + return "Failed to crack" if config.verbosity < 0: return res.path[-1].result.value else: return iface.pretty_search_results(res) ===========changed ref 1=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 2=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 3=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 4=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 5=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 6=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} -
ciphey.basemods.Searchers.ausearch/AuSearch.search
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<del> deadline = ( <1>:<del> datetime.now() + self._config().objs["timeout"] <2>:<del> if self._config().timeout is not None <3>:<del> else datetime.max <4>:<del> ) <5>:<add> logger.trace(f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""") <6>:<del> success, expand_res = self.expand( <7>:<del> [SearchLevel(name="input", result=CrackResult(value=ctext))] <8>:<add> try: <del> ) <9>:<add> root = Node.root(self._config(), ctext) <add> except DuplicateNode: <del> if success: <10>:<add> return None <del> return expand_res <12>:<add> if type(ctext) == self._config().objs["format"]["out"]: <add> check_res = self._config().objs["checker"](ctext) <add> if check_res is not None: <add> return SearchResult(check_res=check_res, path=[root.level]) <del> nodes = set(expand_res) <14>:<add> try: <add> self.recursive_expand(root) <del> while datetime.now() < deadline: <15>:<del> # logger.trace(f"Have node tree {nodes}") <17>:<add> while True: <add> if self.work.empty(): <add> break <add> # Get the highest level result <add> chunk = self.work.get_work_chunk() <add> infos = [i.info for i in chunk] <add> # Work through all of this level's results
# module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def search(self, ctext: Any) -> Optional[SearchResult]: - def search(self, ctext: Any) -> List[SearchLevel]: <0> deadline = ( <1> datetime.now() + self._config().objs["timeout"] <2> if self._config().timeout is not None <3> else datetime.max <4> ) <5> <6> success, expand_res = self.expand( <7> [SearchLevel(name="input", result=CrackResult(value=ctext))] <8> ) <9> if success: <10> return expand_res <11> <12> nodes = set(expand_res) <13> <14> while datetime.now() < deadline: <15> # logger.trace(f"Have node tree {nodes}") <16> <17> if len(nodes) == 0: <18> raise LookupError("Could not find any solutions") <19> <20> best_node = self.findBestNode(nodes) <21> nodes.remove(best_node) <22> success, eval_res = self.evaluate(best_node) <23> if success: <24> # logger.trace(f"Success with node {best_node}") <25> return eval_res <26> nodes.update(eval_res) <27> <28> raise TimeoutError("Search ran out of time") <29>
===========unchanged ref 0=========== at: ciphey.basemods.Searchers.ausearch.AuSearch findBestNode(nodes: Set[Node]) -> Node expand(parents: List[SearchLevel], check: bool=True) -> (bool, Union[SearchResult, List[Node]]) evaluate(node: Node) -> (bool, Union[List[SearchLevel], List[Node]]) at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) SearchLevel(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.ConfigurableModule _config() at: ciphey.iface._modules.Searcher search(self, ctext: Any) -> SearchResult at: datetime datetime() at: datetime.datetime max: ClassVar[datetime] __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - def evaluate(self, node: Node) -> (bool, Union[List[SearchLevel], List[Node]]): - # logger.debug(f"Evaluating {node}") - - res = node.cracker.attemptCrack(node.parents[-1].result.value) - # Detect if we succeeded, and if deduplication is needed - logger.trace(f"Got {len(res)} results") - - ret = [] - for i in res: - success, res = self.expand( - node.parents - + [SearchLevel(name=type(node.cracker).__name__.lower(), result=i)] - ) - if success: - return True, res - ret.extend(res) - - return False, ret - ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - def expand( - self, parents: List[SearchLevel], check: bool = True - ) -> (bool, Union[SearchResult, List[Node]]): - result = parents[-1].result.value - # logger.debug(f"Expanding {parents}") - - # Deduplication - if not self._config().cache.mark_ctext(result): - return False, [] - - if check and type(result) == self._final_type: - check_res = self._checker(result) - if check_res is not None: - return True, SearchResult(path=parents, check_res=check_res) - - success, dec_res = self.handleDecodings(result) - if success: - return True, SearchResult(path=parents + [dec_res[0]], check_res=dec_res[1]) - - nodes: List[Node] = [] - - for decoding in dec_res: - # Don't check, as handleDecodings did that for us - success, eval_res = self.expand(parents + [decoding], check=False) - if success: - return True, eval_res - nodes.extend(eval_res) - - crackers: List[Cracker] = registry[Cracker[type(result)]] - expected_time: float - - # Worth doing this check twice to simplify code and allow a early return for decodings - if type(result) == self._final_type: - expected_time = self._checker.getExpectedRuntime(result) - else: - expected_time = 0 - for i in crackers: - cracker = self._config()(i) - nodes.append( - Node( - cracker=cracker, - crack</s> ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - def expand( - self, parents: List[SearchLevel], check: bool = True - ) -> (bool, Union[SearchResult, List[Node]]): # offset: 1 <s>i) - nodes.append( - Node( - cracker=cracker, - crack_info=cracker.getInfo(result), - check_info=expected_time, - parents=parents, - ) - ) - - return False, nodes - ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work(self) -> T: + best_priority = self._sorted_priorities[0] + target = self._queues[best_priority] + ret = target.pop(0) + if len(target) == 0: + self._sorted_priorities.pop() + return ret + ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Edge: + source: Node + route: Union[Cracker, Decoder] + dest: Optional[Node] = None + # Info is not filled in for Decoders + info: Optional[cipheycore.ausearch_edge] = None +
ciphey.basemods.Searchers.ausearch/AuSearch.getParams
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<add> return { <add> "invert_priority": ParamSpec(req=False, <add> desc="Causes more complex encodings to be looked at first. " <add> "Good for deeply buried encodings.", <add> default="False"), <add> "disable_priority": ParamSpec(req=False, <add> desc="Disables the priority queue altogether. " <add> "May be much faster, but will take *very* odd paths", <add> default="True") <add> } <del> pass
# module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): @staticmethod - @abstractmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> pass <1>
===========unchanged ref 0=========== at: abc abstractmethod(callable: _FuncT) -> _FuncT at: ciphey.iface._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.ConfigurableModule getParams() -> Optional[Dict[str, ParamSpec]] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: ciphey.iface._modules class ParamSpec(NamedTuple): """ Attributes: req Whether this argument is required desc A description of what this argument does default The default value for this argument. Ignored if req == True or configPath is not None config_ref The path to the config that should be the default value list Whether this parameter is in the form of a list, and can therefore be specified more than once visible Whether the user can tweak this via the command line """ req: bool desc: str default: Optional[Any] = None list: bool = False config_ref: Optional[List[str]] = None + visible: bool = True - visible: bool = False ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work(self) -> T: + best_priority = self._sorted_priorities[0] + target = self._queues[best_priority] + ret = target.pop(0) + if len(target) == 0: + self._sorted_priorities.pop() + return ret + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Edge: + source: Node + route: Union[Cracker, Decoder] + dest: Optional[Node] = None + # Info is not filled in for Decoders + info: Optional[cipheycore.ausearch_edge] = None + ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def add_work(self, priority: PriorityType, work: List[T]) -> None: + idx = bisect.bisect_left(self._sorted_priorities, priority) + if idx == len(self._sorted_priorities) or self._sorted_priorities[idx] != priority: + self._sorted_priorities.insert(idx, priority) + self._queues.setdefault(priority, []).extend(work) + ===========changed ref 13=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 16=========== <s>.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + # def expand(self, edge: Edge) -> List[Edge]: + # """Evaluates the destination of the given, and adds its child edges to the pool""" + # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) + + def expand_crackers(self, node: Node) -> None: + res = node.level.result.value + + additional_work = [] + + for i in self.get_crackers_for(type(res)): + inst = self._config()(i) + additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + if self.disable_priority: + priority = 0 + elif self.invert_priority: + priority = -node.depth + else: + priority = node.depth + + self.work.add_work(priority, additional_work) + ===========changed ref 17=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) -
ciphey.basemods.Searchers.ausearch/AuSearch.__init__
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<1>:<add> self._checker: Checker = config.objs["checker"] <del> self._checker = config.objs["checker"] <2>:<add> self._target_type: type = config.objs["format"]["out"] <del> self._final_type = config.objs["format"]["out"] <3>:<add> self.work = PriorityWorkQueue() # Has to be defined here because of sharing <add> self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) <add> self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"]))
# module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod def __init__(self, config: Config): <0> super().__init__(config) <1> self._checker = config.objs["checker"] <2> self._final_type = config.objs["format"]["out"] <3>
===========unchanged ref 0=========== at: abc abstractmethod(callable: _FuncT) -> _FuncT at: ciphey.iface._config Config() at: ciphey.iface._config.Config verbosity: int = 0 searcher: str = "perfection" params: Dict[str, Dict[str, Union[str, List[str]]]] = {} format: Dict[str, str] = {"in": "str", "out": "str"} modules: List[str] = [] checker: str = "ezcheck" default_dist: str = "cipheydists::dist::twist" timeout: Optional[int] = None _inst: Dict[type, Any] = {} objs: Dict[str, Any] = {} cache: Cache = Cache() at: ciphey.iface._modules.Searcher __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.iface._config class Config: - verbosity: int = 0 - searcher: str = "perfection" - params: Dict[str, Dict[str, Union[str, List[str]]]] = {} - format: Dict[str, str] = {"in": "str", "out": "str"} - modules: List[str] = [] - checker: str = "ezcheck" - default_dist: str = "cipheydists::dist::twist" - timeout: Optional[int] = None - - _inst: Dict[type, Any] = {} - objs: Dict[str, Any] = {} - cache: Cache = Cache() - ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work(self) -> T: + best_priority = self._sorted_priorities[0] + target = self._queues[best_priority] + ret = target.pop(0) + if len(target) == 0: + self._sorted_priorities.pop() + return ret + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): @staticmethod - @abstractmethod def getParams() -> Optional[Dict[str, ParamSpec]]: + return { + "invert_priority": ParamSpec(req=False, + desc="Causes more complex encodings to be looked at first. " + "Good for deeply buried encodings.", + default="False"), + "disable_priority": ParamSpec(req=False, + desc="Disables the priority queue altogether. " + "May be much faster, but will take *very* odd paths", + default="True") + } - pass ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Edge: + source: Node + route: Union[Cracker, Decoder] + dest: Optional[Node] = None + # Info is not filled in for Decoders + info: Optional[cipheycore.ausearch_edge] = None + ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 13=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def add_work(self, priority: PriorityType, work: List[T]) -> None: + idx = bisect.bisect_left(self._sorted_priorities, priority) + if idx == len(self._sorted_priorities) or self._sorted_priorities[idx] != priority: + self._sorted_priorities.insert(idx, priority) + self._queues.setdefault(priority, []).extend(work) + ===========changed ref 14=========== <s>.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + # def expand(self, edge: Edge) -> List[Edge]: + # """Evaluates the destination of the given, and adds its child edges to the pool""" + # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) + + def expand_crackers(self, node: Node) -> None: + res = node.level.result.value + + additional_work = [] + + for i in self.get_crackers_for(type(res)): + inst = self._config()(i) + additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + if self.disable_priority: + priority = 0 + elif self.invert_priority: + priority = -node.depth + else: + priority = node.depth + + self.work.add_work(priority, additional_work) +
ciphey.basemods.Decoders.binary/Binary.try_split
Added
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<add> ret = [] <add> <add> for i in split_text: <add> if len(i) == 0: <add> continue <add> val = int(i, 2) <add> if val > 255 or val < 0: <add> return None <add> ret.append(val) <add> <add> if len(ret) != 0: <add> ret = bytes(ret) <add> logger.debug(f"binary successful, returning {ret.__repr__()}") <add> return ret <add>
# module: ciphey.basemods.Decoders.binary @registry.register class Binary(ciphey.iface.Decoder[str, bytes]): + def try_split(self, split_text: List[str]): <0> <extra_id_1><extra_id_2><extra_id_3><extra_id_4><extra_id_5><extra_id_6><extra_id_7><extra_id_8><extra_id_9><extra_id_10><extra_id_11><extra_id_12><extra_id_13><extra_id_14>
===========unchanged ref 0=========== at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 5=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 6=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 8=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 9=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 10=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 12=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 13=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 17=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 18=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 19=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 20=========== # module: ciphey.basemods.Searchers.ausearch + """ + We are using a tree structure here, because that makes searching and tracing back easier + + As such, when we encounter another possible parent, we remove that edge + """ + + PriorityType = TypeVar('PriorityType') ===========changed ref 21=========== # module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): + """This does all the loading for the config, and then returns itself""" self.load_modules() self.load_objs() self.update_log_level(self.verbosity) + return self ===========changed ref 22=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Edge: + source: Node + route: Union[Cracker, Decoder] + dest: Optional[Node] = None + # Info is not filled in for Decoders + info: Optional[cipheycore.ausearch_edge] = None + ===========changed ref 23=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work(self) -> T: + best_priority = self._sorted_priorities[0] + target = self._queues[best_priority] + ret = target.pop(0) + if len(target) == 0: + self._sorted_priorities.pop() + return ret + ===========changed ref 24=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + # The root has no parent edge + level: SearchLevel + parent: Optional['Edge'] = None + depth: int = 0 - cracker: Cracker - parents: List[SearchLevel] - crack_info: CrackInfo - check_info: float ===========changed ref 25=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def add_work(self, priority: PriorityType, work: List[T]) -> None: + idx = bisect.bisect_left(self._sorted_priorities, priority) + if idx == len(self._sorted_priorities) or self._sorted_priorities[idx] != priority: + self._sorted_priorities.insert(idx, priority) + self._queues.setdefault(priority, []).extend(work) +
ciphey.basemods.Decoders.binary/Binary.try_split
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<add> ret = [] <add> <add> for i in split_text: <add> if len(i) == 0: <add> continue <add> val = int(i, 2) <add> if val > 255 or val < 0: <add> return None <add> ret.append(val) <add> <add> if len(ret) != 0: <add> ret = bytes(ret) <add> logger.debug(f"binary successful, returning {ret.__repr__()}") <add> return ret <add>
# module: ciphey.basemods.Decoders.binary @registry.register class Binary(ciphey.iface.Decoder[str, bytes]): + def try_split(self, split_text: List[str]): <0> <extra_id_1><extra_id_2><extra_id_3><extra_id_4><extra_id_5><extra_id_6><extra_id_7><extra_id_8><extra_id_9><extra_id_10><extra_id_11><extra_id_12><extra_id_13><extra_id_14>
===========unchanged ref 0=========== at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Decoders.binary @registry.register class Binary(ciphey.iface.Decoder[str, bytes]): + def try_split(self, split_text: List[str]): + ret = [] + + for i in split_text: + if len(i) == 0: + continue + val = int(i, 2) + if val > 255 or val < 0: + return None + ret.append(val) + + if len(ret) != 0: + ret = bytes(ret) + logger.debug(f"binary successful, returning {ret.__repr__()}") + return ret + ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 6=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 7=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 9=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 10=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 11=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 13=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 17=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 18=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 19=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 20=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 21=========== # module: ciphey.basemods.Searchers.ausearch + """ + We are using a tree structure here, because that makes searching and tracing back easier + + As such, when we encounter another possible parent, we remove that edge + """ + + PriorityType = TypeVar('PriorityType') ===========changed ref 22=========== # module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): + """This does all the loading for the config, and then returns itself""" self.load_modules() self.load_objs() self.update_log_level(self.verbosity) + return self ===========changed ref 23=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Edge: + source: Node + route: Union[Cracker, Decoder] + dest: Optional[Node] = None + # Info is not filled in for Decoders + info: Optional[cipheycore.ausearch_edge] = None + ===========changed ref 24=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work(self) -> T: + best_priority = self._sorted_priorities[0] + target = self._queues[best_priority] + ret = target.pop(0) + if len(target) == 0: + self._sorted_priorities.pop() + return ret +
ciphey.basemods.Crackers.vigenere/Vigenere.getInfo
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<13>:<add> <add> likely_lens = self.cache.get_or_update( <add> ctext, <add> f"vigenere::likely_lens", <add> lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value), <add> ) <add> <add> for keysize in likely_lens: <add> # Store the analysis <add> analysis = self.cache.get_or_update( <add> ctext, <add> f"vigenere::{keysize.len}", <add> lambda: keysize.tab <add> ) <add> if len(likely_lens) == 0: <del> else: <15>:<add> success_likelihood=0, <del> success_likelihood=0.5, # TODO: actually work this out <17>:<add> success_runtime=2e-4, <del> success_runtime=1e-4, <18>:<add> failure_runtime=2e-4, <del> failure_runtime=1e-4,
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): + def getInfo(self, ctext: str) -> CrackInfo: - def getInfo(self, ctext: T) -> CrackInfo: <0> if self.keysize is not None: <1> analysis = self.cache.get_or_update( <2> ctext, <3> f"vigenere::{self.keysize}", <4> lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), <5> ) <6> <7> return CrackInfo( <8> success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), <9> # TODO: actually calculate runtimes <10> success_runtime=1e-4, <11> failure_runtime=1e-4, <12> ) <13> else: <14> return CrackInfo( <15> success_likelihood=0.5, # TODO: actually work this out <16> # TODO: actually calculate runtimes <17> success_runtime=1e-4, <18> failure_runtime=1e-4, <19> ) <20>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.keysize = self._params().get("keysize") self.keysize = int(self.keysize) self.p_value = self._params()["p_value"] at: ciphey.iface._config.Cache _cache: Dict[Any, Dict[str, Any]] = {} get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) at: ciphey.iface._modules CrackInfo(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) Cracker(config: Config) at: ciphey.iface._modules.Cracker getInfo(self, ctext: T) -> CrackInfo ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 5=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 6=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 8=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 9=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 10=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 12=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 13=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 17=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 18=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 19=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 20=========== # module: ciphey.basemods.Searchers.ausearch + """ + We are using a tree structure here, because that makes searching and tracing back easier + + As such, when we encounter another possible parent, we remove that edge + """ + + PriorityType = TypeVar('PriorityType') ===========changed ref 21=========== # module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): + """This does all the loading for the config, and then returns itself""" self.load_modules() self.load_objs() self.update_log_level(self.verbosity) + return self ===========changed ref 22=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Edge: + source: Node + route: Union[Cracker, Decoder] + dest: Optional[Node] = None + # Info is not filled in for Decoders + info: Optional[cipheycore.ausearch_edge] = None + ===========changed ref 23=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work(self) -> T: + best_priority = self._sorted_priorities[0] + target = self._queues[best_priority] + ret = target.pop(0) + if len(target) == 0: + self._sorted_priorities.pop() + return ret +
ciphey.basemods.Crackers.vigenere/Vigenere.attemptCrack
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<19>:<add> likely_lens = self.cache.get_or_update( <add> ctext, <add> f"vigenere::likely_lens", <add> lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group), <add> ) <add> possible_lens = [i for i in likely_lens] <add> possible_lens.sort(key=lambda i: i.p_value) <del> possible_len = self.kasiskiExamination(message) <20>:<del> possible_len.sort() <21>:<add> logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") <del> logger.trace(f"Got possible lengths {possible_len}") <23>:<add> for i in possible_lens: <del> for i in possible_len: <29>:<add> f"vigenere::{i.len}", <del> f"vigenere::{i}", <30>:<add> lambda: cipheycore.analyse_string(ctext, i.len, self.group), <del> lambda: cipheycore.analyse_string(ctext, i, self.group),
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> logger.debug("Trying vigenere cipher") <1> # Convert it to lower case <2> if self.lower: <3> message = ctext.lower() <4> else: <5> message = ctext <6> <7> # Analysis must be done here, where we know the case for the cache <8> if self.keysize is not None: <9> return self.crackOne( <10> message, <11> self.cache.get_or_update( <12> ctext, <13> f"vigenere::{self.keysize}", <14> lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), <15> ), <16> ) <17> else: <18> arrs = [] <19> possible_len = self.kasiskiExamination(message) <20> possible_len.sort() <21> logger.trace(f"Got possible lengths {possible_len}") <22> # TODO: work out length <23> for i in possible_len: <24> arrs.extend( <25> self.crackOne( <26> message, <27> self.cache.get_or_update( <28> ctext, <29> f"vigenere::{i}", <30> lambda: cipheycore.analyse_string(ctext, i, self.group), <31> ), <32> ) <33> ) <34> <35> logger.debug(f"Vigenere returned {len(arrs)} candidates") <36> return arrs <37>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.lower: Union[str, bool] = self._params()["lower"] self.lower = util.strtobool(self.lower) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.keysize = self._params().get("keysize") self.keysize = int(self.keysize) self.p_value = self._params()["p_value"] at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker attemptCrack(self, ctext: T) -> List[CrackResult] at: ciphey.iface._modules.Targeted getTarget() -> str at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): + def getInfo(self, ctext: str) -> CrackInfo: - def getInfo(self, ctext: T) -> CrackInfo: if self.keysize is not None: analysis = self.cache.get_or_update( ctext, f"vigenere::{self.keysize}", lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), ) return CrackInfo( success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes success_runtime=1e-4, failure_runtime=1e-4, ) + + likely_lens = self.cache.get_or_update( + ctext, + f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value), + ) + + for keysize in likely_lens: + # Store the analysis + analysis = self.cache.get_or_update( + ctext, + f"vigenere::{keysize.len}", + lambda: keysize.tab + ) + if len(likely_lens) == 0: - else: return CrackInfo( + success_likelihood=0, - success_likelihood=0.5, # TODO: actually work this out # TODO: actually calculate runtimes + success_runtime=2e-4, - success_runtime=1e-4, + failure_runtime=2e-4, - failure_runtime=1e-4, ) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 6=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 7=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 9=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 10=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 11=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 13=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 17=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 18=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 19=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} -
ciphey.basemods.Crackers.vigenere/Vigenere.getParams
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<23>:<add> default=0.01, <del> default=0.99,
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> return { <1> "expected": ciphey.iface.ParamSpec( <2> desc="The expected distribution of the plaintext", <3> req=False, <4> config_ref=["default_dist"], <5> ), <6> "group": ciphey.iface.ParamSpec( <7> desc="An ordered sequence of chars that make up the caesar cipher alphabet", <8> req=False, <9> default="abcdefghijklmnopqrstuvwxyz", <10> ), <11> "lower": ciphey.iface.ParamSpec( <12> desc="Whether or not the ciphertext should be converted to lowercase first", <13> req=False, <14> default=True, <15> ), <16> "keysize": ciphey.iface.ParamSpec( <17> desc="A key size that should be used. If not given, will attempt to work it out", <18> req=False, <19> ), <20> "p_value": ciphey.iface.ParamSpec( <21> desc="The p-value to use for windowed frequency analysis", <22> req=False, <23> default=0.99, <24> ), <25> } <26>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere crackOne(ctext: str, analysis: cipheycore.windowed_analysis_res) -> List[CrackResult] crackOne(self, ctext: str, analysis: cipheycore.windowed_analysis_res) -> List[CrackResult] at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.keysize = self._params().get("keysize") self.keysize = int(self.keysize) at: ciphey.basemods.Crackers.vigenere.Vigenere.attemptCrack message = ctext message = ctext.lower() at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) ===========changed ref 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): + def getInfo(self, ctext: str) -> CrackInfo: - def getInfo(self, ctext: T) -> CrackInfo: if self.keysize is not None: analysis = self.cache.get_or_update( ctext, f"vigenere::{self.keysize}", lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), ) return CrackInfo( success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes success_runtime=1e-4, failure_runtime=1e-4, ) + + likely_lens = self.cache.get_or_update( + ctext, + f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value), + ) + + for keysize in likely_lens: + # Store the analysis + analysis = self.cache.get_or_update( + ctext, + f"vigenere::{keysize.len}", + lambda: keysize.tab + ) + if len(likely_lens) == 0: - else: return CrackInfo( + success_likelihood=0, - success_likelihood=0.5, # TODO: actually work this out # TODO: actually calculate runtimes + success_runtime=2e-4, - success_runtime=1e-4, + failure_runtime=2e-4, - failure_runtime=1e-4, ) ===========changed ref 1=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: logger.debug("Trying vigenere cipher") # Convert it to lower case if self.lower: message = ctext.lower() else: message = ctext # Analysis must be done here, where we know the case for the cache if self.keysize is not None: return self.crackOne( message, self.cache.get_or_update( ctext, f"vigenere::{self.keysize}", lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), ), ) else: arrs = [] + likely_lens = self.cache.get_or_update( + ctext, + f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group), + ) + possible_lens = [i for i in likely_lens] + possible_lens.sort(key=lambda i: i.p_value) - possible_len = self.kasiskiExamination(message) - possible_len.sort() + logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") - logger.trace(f"Got possible lengths {possible_len}") # TODO: work out length + for i in possible_lens: - for i in possible_len: arrs.extend( self.crackOne( message, self.cache.get_or_update( ctext, + f"vigenere::{i.len}", - f"vigenere::{i}", + lambda: ciph</s> ===========changed ref 2=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 <s>enere::{i.len}", - f"vigenere::{i}", + lambda: cipheycore.analyse_string(ctext, i.len, self.group), - lambda: cipheycore.analyse_string(ctext, i, self.group), ), ) ) logger.debug(f"Vigenere returned {len(arrs)} candidates") return arrs ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 8=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 9=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 11=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} +
ciphey.basemods.Checkers.ezcheck/EzCheck.__init__
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<1>:<add> <add> self.checkers: List[Checker[str]] = []
# module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): def __init__(self, config: Config): <0> super().__init__(config) <1> <2> # We need to modify the config for each of the objects <3> <4> # First the flag regexes, as they are the fastest <5> flags_config = config <6> flags_config.update_param("regexlist", "resource", "cipheydists::list::flags") <7> # We do not cache, as this uses a different, on-time config <8> self.checkers.append(RegexList(flags_config)) <9> <10> # Next, the json checker <11> self.checkers.append(config(JsonChecker)) <12> <13> # Finally, the Brandon checker, as it is the slowest <14> self.checkers.append(config(Brandon)) <15>
===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon Brandon(config: ciphey.iface.Config) at: ciphey.basemods.Checkers.format JsonChecker(config: Config) at: ciphey.basemods.Checkers.regex RegexList(config: Config) at: ciphey.iface._config.Config verbosity: int = 0 searcher: str = "perfection" params: Dict[str, Dict[str, Union[str, List[str]]]] = {} format: Dict[str, str] = {"in": "str", "out": "str"} modules: List[str] = [] checker: str = "ezcheck" default_dist: str = "cipheydists::dist::twist" timeout: Optional[int] = None _inst: Dict[type, Any] = {} objs: Dict[str, Any] = {} cache: Cache = Cache() update_param(owner: str, name: str, value: Optional[Any]) at: ciphey.iface._modules Checker(config: Config) at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): - checkers: List[Checker[str]] = [] - """ This object is effectively a prebuilt quroum (with requirement 1) of common patterns """ ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 6=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 7=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 9=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 10=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 11=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 13=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 17=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 18=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 19=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 20=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 21=========== # module: ciphey.basemods.Searchers.ausearch + """ + We are using a tree structure here, because that makes searching and tracing back easier + + As such, when we encounter another possible parent, we remove that edge + """ + + PriorityType = TypeVar('PriorityType') ===========changed ref 22=========== # module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): + """This does all the loading for the config, and then returns itself""" self.load_modules() self.load_objs() self.update_log_level(self.verbosity) + return self ===========changed ref 23=========== + # module: tools.freq_analysis + data = sys.stdin.read() + + analysis = cipheycore.analyse_string(data) + + print(json.dumps({i: j / len(data) for i, j in analysis.freqs.items()})) +
tests.test_main/test_caesar
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<del> runner = CliRunner() <1>:<del> result = runner.invoke( <2>:<del> main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], <3>:<del> ) <4>:<del> assert result.exit_code == 0 <5>:<del> assert "dog" in result.output <6>:<add> res = decrypt(Config().library_default().complete_config(), <add> "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr") <add> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_caesar(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], <3> ) <4> assert result.exit_code == 0 <5> assert "dog" in result.output <6>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> List[SearchLevel] at: ciphey.iface._config Config() at: tests.test_main answer_str = "Hello my name is bee and I like dog and apple and tree".lower() at: tests.test_main.test_binary_base64_caesar res = decrypt(Config().library_default().complete_config(), "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " "01000010 01101110 01011010 01011000 01001010 01111001 00001010") ===========changed ref 0=========== # module: ciphey.ciphey + def decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes]: - def decrypt(config: iface.Config, ctext: Any) -> List[SearchLevel]: """A simple alias for searching a ctext and makes the answer pretty""" + res: Optional[iface.SearchResult] = config.objs["searcher"].search(ctext) - res: iface.SearchResult = config.objs["searcher"].search(ctext) + if res is None: + return "Failed to crack" if config.verbosity < 0: return res.path[-1].result.value else: return iface.pretty_search_results(res) ===========changed ref 1=========== # module: ciphey.iface._config class Config: - verbosity: int = 0 - searcher: str = "perfection" - params: Dict[str, Dict[str, Union[str, List[str]]]] = {} - format: Dict[str, str] = {"in": "str", "out": "str"} - modules: List[str] = [] - checker: str = "ezcheck" - default_dist: str = "cipheydists::dist::twist" - timeout: Optional[int] = None - - _inst: Dict[type, Any] = {} - objs: Dict[str, Any] = {} - cache: Cache = Cache() - ===========changed ref 2=========== # module: tests.test_main + def test_plaintext(): + res = decrypt(Config.library_default().complete_config(), answer_str) + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 3=========== # module: tests.test_main + def test_base64(): + res = decrypt(Config().library_default().complete_config(), + "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl") + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 4=========== # module: tests.test_main - def test_base16(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", - "-q", - ] - ) - assert result.exit_code == 0 - assert "dog" in result.output - ===========changed ref 5=========== # module: tests.test_main - def test_initial(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", - "-q", - ], - ) - print(result) - print(result.output) - assert result.exit_code == 0 - print(result.output) - assert "dog" in result.output - ===========changed ref 6=========== # module: tests.test_main + def test_binary_base64_caesar(): + res = decrypt(Config().library_default().complete_config(), + "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " + "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " + "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " + "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " + "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " + "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " + "01000010 01101110 01011010 01011000 01001010 01111001 00001010") + assert res.lower() == answer_str.lower() + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 +
tests.test_main/test_vigenere
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<del> runner = CliRunner() <1>:<del> result = runner.invoke( <2>:<del> main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-q"], <3>:<del> ) <4>:<del> assert result.exit_code == 0 <5>:<del> assert "dog" in result.output <6>:<add> res = decrypt(Config().library_default().complete_config(), <add> "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic") <add> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_vigenere(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-q"], <3> ) <4> assert result.exit_code == 0 <5> assert "dog" in result.output <6>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> List[SearchLevel] at: ciphey.iface._config Config() at: tests.test_main answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 0=========== # module: ciphey.ciphey + def decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes]: - def decrypt(config: iface.Config, ctext: Any) -> List[SearchLevel]: """A simple alias for searching a ctext and makes the answer pretty""" + res: Optional[iface.SearchResult] = config.objs["searcher"].search(ctext) - res: iface.SearchResult = config.objs["searcher"].search(ctext) + if res is None: + return "Failed to crack" if config.verbosity < 0: return res.path[-1].result.value else: return iface.pretty_search_results(res) ===========changed ref 1=========== # module: ciphey.iface._config class Config: - verbosity: int = 0 - searcher: str = "perfection" - params: Dict[str, Dict[str, Union[str, List[str]]]] = {} - format: Dict[str, str] = {"in": "str", "out": "str"} - modules: List[str] = [] - checker: str = "ezcheck" - default_dist: str = "cipheydists::dist::twist" - timeout: Optional[int] = None - - _inst: Dict[type, Any] = {} - objs: Dict[str, Any] = {} - cache: Cache = Cache() - ===========changed ref 2=========== # module: tests.test_main + def test_plaintext(): + res = decrypt(Config.library_default().complete_config(), answer_str) + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 3=========== # module: tests.test_main + def test_base64(): + res = decrypt(Config().library_default().complete_config(), + "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl") + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 4=========== # module: tests.test_main def test_caesar(): - runner = CliRunner() - result = runner.invoke( - main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], - ) - assert result.exit_code == 0 - assert "dog" in result.output + res = decrypt(Config().library_default().complete_config(), + "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr") + assert res.lower() == answer_str.lower() ===========changed ref 5=========== # module: tests.test_main - def test_base16(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", - "-q", - ] - ) - assert result.exit_code == 0 - assert "dog" in result.output - ===========changed ref 6=========== # module: tests.test_main - def test_initial(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", - "-q", - ], - ) - print(result) - print(result.output) - assert result.exit_code == 0 - print(result.output) - assert "dog" in result.output - ===========changed ref 7=========== # module: tests.test_main + def test_binary_base64_caesar(): + res = decrypt(Config().library_default().complete_config(), + "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " + "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " + "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " + "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " + "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " + "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " + "01000010 01101110 01011010 01011000 01001010 01111001 00001010") + assert res.lower() == answer_str.lower() + ===========changed ref 8=========== # module: tests.test_main - def test_base64_caesar(): - runner = CliRunner() - result = runner.invoke( - main, - [ - "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100 01011000 01010001 01100111 01010011 01010011 01000010 01101000 01100010 01001000 01001110 01110110 01001001 01000111 01010010 01110110 01001001 01000111 01101000 01101000 01100011 01001000 01000010 01101100 01100010 01101001 01000010 00110000 01100010 01111001 01000010 01101100 01100010 01101101 01110000 01110110 01100101 01010011 01000010 00110011 01011001 01010111 01111000 01110010 01100011 01110111 00111101 00111101", - "-q", - ], - ) - assert result.exit_code == 0 - assert "dog" in result.output -
tests.test_main/test_binary
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<del> runner = CliRunner() <1>:<del> result = runner.invoke( <2>:<del> main, <3>:<del> [ <4>:<del> "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100", <5>:<del> "-q", <6>:<del> ], <7>:<del> ) <8>:<del> assert result.exit_code == 0 <9>:<del> assert "dog" in result.output <10>:<add> res = decrypt(Config().library_default().complete_config(), <add> "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 " <add> "01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 " <add> "01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 " <add> "01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100001 01110000 01110000 01101100 " <add> "01100101 00100000 01100001 01101110 01100100 00100000 01110100 01110010 01100101 011
# module: tests.test_main def test_binary(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, <3> [ <4> "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100", <5> "-q", <6> ], <7> ) <8> assert result.exit_code == 0 <9> assert "dog" in result.output <10>
===========changed ref 0=========== # module: tests.test_main + def test_plaintext(): + res = decrypt(Config.library_default().complete_config(), answer_str) + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 1=========== # module: tests.test_main def test_vigenere(): - runner = CliRunner() - result = runner.invoke( - main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-q"], - ) - assert result.exit_code == 0 - assert "dog" in result.output + res = decrypt(Config().library_default().complete_config(), + "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic") + assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main + def test_base64(): + res = decrypt(Config().library_default().complete_config(), + "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl") + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 3=========== # module: tests.test_main def test_caesar(): - runner = CliRunner() - result = runner.invoke( - main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], - ) - assert result.exit_code == 0 - assert "dog" in result.output + res = decrypt(Config().library_default().complete_config(), + "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr") + assert res.lower() == answer_str.lower() ===========changed ref 4=========== # module: tests.test_main - def test_base16(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", - "-q", - ] - ) - assert result.exit_code == 0 - assert "dog" in result.output - ===========changed ref 5=========== # module: tests.test_main - def test_initial(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", - "-q", - ], - ) - print(result) - print(result.output) - assert result.exit_code == 0 - print(result.output) - assert "dog" in result.output - ===========changed ref 6=========== # module: tests.test_main + def test_binary_base64_caesar(): + res = decrypt(Config().library_default().complete_config(), + "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " + "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " + "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " + "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " + "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " + "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " + "01000010 01101110 01011010 01011000 01001010 01111001 00001010") + assert res.lower() == answer_str.lower() + ===========changed ref 7=========== # module: tests.test_main - def test_base64_caesar(): - runner = CliRunner() - result = runner.invoke( - main, - [ - "01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01100010 01011000 01101011 01100111 01100010 01101101 01000110 01110100 01011010 01010011 01000010 01110000 01100011 01111001 01000010 01101001 01011010 01010111 01010101 01100111 01011001 01010111 00110101 01101011 01001001 01000101 01101011 01100111 01100010 01000111 01101100 01110010 01011010 01010011 01000010 01101011 01100010 00110010 01100011 01100111 01011001 01010111 00110101 01101011 01001001 01000111 01001110 01101000 01100100 01000011 01000010 01101001 01100100 01011000 01010001 01100111 01010011 01010011 01000010 01101000 01100010 01001000 01001110 01110110 01001001 01000111 01010010 01110110 01001001 01000111 01101000 01101000 01100011 01001000 01000010 01101100 01100010 01101001 01000010 00110000 01100010 01111001 01000010 01101100 01100010 01101101 01110000 01110110 01100101 01010011 01000010 00110011 01011001 01010111 01111000 01110010 01100011 01110111 00111101 00111101", - "-q", - ], - ) - assert result.exit_code == 0 - assert "dog" in result.output - ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str +
tests.test_main/test_hex
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<0>:<del> runner = CliRunner() <1>:<del> result = runner.invoke( <2>:<del> main, <3>:<del> [ <4>:<del> "48 65 6c 6c 6f 20 6d 79 20 6e 61 6d 65 20 69 73 20 62 65 65 20 61 6e 64 20 49 20 6c 69 6b 65 20 64 6f 67 20 61 6e 64 20 63 61 74", <5>:<del> "-q", <6>:<del> ], <7>:<del> ) <8>:<del> assert result.exit_code == 0 <9>:<del> assert "dog" in result.output <10>:<add> res = decrypt(Config().library_default().complete_config(), <add> "48656c6c6f206d79206e616d652069732062656520616e642049206c696b6520646f6720616e64206170706c6520616e6420" <add> "74726565")
# module: tests.test_main def test_hex(): <0> runner = CliRunner() <1> result = runner.invoke( <2> main, <3> [ <4> "48 65 6c 6c 6f 20 6d 79 20 6e 61 6d 65 20 69 73 20 62 65 65 20 61 6e 64 20 49 20 6c 69 6b 65 20 64 6f 67 20 61 6e 64 20 63 61 74", <5> "-q", <6> ], <7> ) <8> assert result.exit_code == 0 <9> assert "dog" in result.output <10>
===========changed ref 0=========== # module: tests.test_main + def test_plaintext(): + res = decrypt(Config.library_default().complete_config(), answer_str) + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 1=========== # module: tests.test_main def test_vigenere(): - runner = CliRunner() - result = runner.invoke( - main, ["Omstv uf vhul qz jlm hvk Q sqrm kwn iul jia", "-q"], - ) - assert result.exit_code == 0 - assert "dog" in result.output + res = decrypt(Config().library_default().complete_config(), + "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic") + assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main + def test_base64(): + res = decrypt(Config().library_default().complete_config(), + "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl") + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 3=========== # module: tests.test_main def test_caesar(): - runner = CliRunner() - result = runner.invoke( - main, ["Uryyb zl anzr vf orr naq V yvxr qbt naq png", "-q"], - ) - assert result.exit_code == 0 - assert "dog" in result.output + res = decrypt(Config().library_default().complete_config(), + "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr") + assert res.lower() == answer_str.lower() ===========changed ref 4=========== # module: tests.test_main - def test_base16(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "JBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLFEBQW4ZBAJEQGY2LLMUQGI33HEBQW4ZBAMNQXI===", - "-q", - ] - ) - assert result.exit_code == 0 - assert "dog" in result.output - ===========changed ref 5=========== # module: tests.test_main - def test_initial(): - runner = CliRunner() - # result = runner.invoke(main, ["hello my name is bee and i like bees"]) - result = runner.invoke( - main, - [ - "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", - "-q", - ], - ) - print(result) - print(result.output) - assert result.exit_code == 0 - print(result.output) - assert "dog" in result.output - ===========changed ref 6=========== # module: tests.test_main + def test_binary_base64_caesar(): + res = decrypt(Config().library_default().complete_config(), + "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " + "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " + "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " + "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " + "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " + "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " + "01000010 01101110 01011010 01011000 01001010 01111001 00001010") + assert res.lower() == answer_str.lower() + ===========changed ref 7=========== # module: tests.test_main def test_binary(): - runner = CliRunner() - result = runner.invoke( - main, - [ - "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100", - "-q", - ], - ) - assert result.exit_code == 0 - assert "dog" in result.output + res = decrypt(Config().library_default().complete_config(), + "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 " + "01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 " + "01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 " + "01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100001 01110000 01110000 01101100 " + "01100101 00100000 01100001 01101110 01100100 00100000 01110100 01110010 01100101 01100101")
ciphey.basemods.Crackers.caesar/Caesar.getInfo
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<9>:<add> success_runtime=1e-5, <del> success_runtime=1e-4, <10>:<add> failure_runtime=1e-5, <del> failure_runtime=1e-4,
# module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): + def getInfo(self, ctext: str) -> CrackInfo: - def getInfo(self, ctext: T) -> CrackInfo: <0> analysis = self.cache.get_or_update( <1> ctext, <2> "cipheycore::simple_analysis", <3> lambda: cipheycore.analyse_string(ctext), <4> ) <5> <6> return CrackInfo( <7> success_likelihood=cipheycore.caesar_detect(analysis, self.expected), <8> # TODO: actually calculate runtimes <9> success_runtime=1e-4, <10> failure_runtime=1e-4, <11> ) <12>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.caesar.Caesar.__init__ self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache at: ciphey.iface._config.Cache _cache: Dict[Any, Dict[str, Any]] = {} get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) at: ciphey.iface._modules CrackInfo(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) Cracker(config: Config) at: ciphey.iface._modules.Cracker getInfo(self, ctext: T) -> CrackInfo ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 5=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 6=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 8=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 9=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 10=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 11=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 13=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 17=========== # module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): - checkers: List[Checker[str]] = [] - """ This object is effectively a prebuilt quroum (with requirement 1) of common patterns """ ===========changed ref 18=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 19=========== # module: tests.test_main + def test_plaintext(): + res = decrypt(Config.library_default().complete_config(), answer_str) + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 20=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 21=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 22=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 23=========== # module: ciphey.basemods.Searchers.ausearch + """ + We are using a tree structure here, because that makes searching and tracing back easier + + As such, when we encounter another possible parent, we remove that edge + """ + + PriorityType = TypeVar('PriorityType') ===========changed ref 24=========== # module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): + """This does all the loading for the config, and then returns itself""" self.load_modules() self.load_objs() self.update_log_level(self.verbosity) + return self ===========changed ref 25=========== + # module: tools.freq_analysis + data = sys.stdin.read() + + analysis = cipheycore.analyse_string(data) + + print(json.dumps({i: j / len(data) for i, j in analysis.freqs.items()})) +
ciphey.basemods.Crackers.caesar/Caesar.attemptCrack
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<15>:<add> lambda: cipheycore.analyse_string(ctext), <del> lambda: cipheycore.analyse_string(message), <19>:<add> analysis, self.expected, self.group, self.p_value <del> analysis, self.expected, self.group, True, self.p_value <21>:<add> <23>:<add> <add> if n_candidates == 0: <add> logger.trace(f"Filtering for better results") <add> analysis = cipheycore.analyse_string(ctext, self.group) <add> possible_keys = cipheycore.caesar_crack( <add> analysis, self.expected, self.group, self.p_value <add> ) <27>:<add> logger.trace(f"Candidate {candidate.key} has prob {candidate.p_value}")
# module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> logger.debug("Trying caesar cipher") <1> # Convert it to lower case <2> # <3> # TODO: handle different alphabets <4> if self.lower: <5> message = ctext.lower() <6> else: <7> message = ctext <8> <9> logger.trace("Beginning cipheycore simple analysis") <10> <11> # Hand it off to the core <12> analysis = self.cache.get_or_update( <13> ctext, <14> "cipheycore::simple_analysis", <15> lambda: cipheycore.analyse_string(message), <16> ) <17> logger.trace("Beginning cipheycore::caesar") <18> possible_keys = cipheycore.caesar_crack( <19> analysis, self.expected, self.group, True, self.p_value <20> ) <21> n_candidates = len(possible_keys) <22> logger.debug(f"Caesar returned {n_candidates} candidates") <23> <24> candidates = [] <25> <26> for candidate in possible_keys: <27> translated = cipheycore.caesar_decrypt(message, candidate.key, self.group) <28> candidates.append(CrackResult(value=translated, key_info=candidate.key)) <29> <30> return candidates <31>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.caesar.Caesar.__init__ self.lower: Union[str, bool] = self._params()["lower"] self.lower = util.strtobool(self.lower) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.p_value = self._params()["p_value"] at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker attemptCrack(self, ctext: T) -> List[CrackResult] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): + def getInfo(self, ctext: str) -> CrackInfo: - def getInfo(self, ctext: T) -> CrackInfo: analysis = self.cache.get_or_update( ctext, "cipheycore::simple_analysis", lambda: cipheycore.analyse_string(ctext), ) return CrackInfo( success_likelihood=cipheycore.caesar_detect(analysis, self.expected), # TODO: actually calculate runtimes + success_runtime=1e-5, - success_runtime=1e-4, + failure_runtime=1e-5, - failure_runtime=1e-4, ) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 6=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 7=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 9=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 10=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 11=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 12=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 13=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 14=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 17=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 18=========== # module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): - checkers: List[Checker[str]] = [] - """ This object is effectively a prebuilt quroum (with requirement 1) of common patterns """ ===========changed ref 19=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 20=========== # module: tests.test_main + def test_plaintext(): + res = decrypt(Config.library_default().complete_config(), answer_str) + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 21=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 22=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 23=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret +
ciphey.basemods.Crackers.caesar/Caesar.getParams
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<19>:<add> default=0.01, <del> default=0.1,
# module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> return { <1> "expected": ciphey.iface.ParamSpec( <2> desc="The expected distribution of the plaintext", <3> req=False, <4> config_ref=["default_dist"], <5> ), <6> "group": ciphey.iface.ParamSpec( <7> desc="An ordered sequence of chars that make up the caesar cipher alphabet", <8> req=False, <9> default="abcdefghijklmnopqrstuvwxyz", <10> ), <11> "lower": ciphey.iface.ParamSpec( <12> desc="Whether or not the ciphertext should be converted to lowercase first", <13> req=False, <14> default=True, <15> ), <16> "p_value": ciphey.iface.ParamSpec( <17> desc="The p-value to use for standard frequency analysis", <18> req=False, <19> default=0.1, <20> ) <21> # TODO: add "filter" param <22> } <23>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.caesar.Caesar.__init__ self.group = list(self._params()["group"]) at: ciphey.basemods.Crackers.caesar.Caesar.attemptCrack message = ctext message = ctext.lower() possible_keys = cipheycore.caesar_crack( analysis, self.expected, self.group, self.p_value ) possible_keys = cipheycore.caesar_crack( analysis, self.expected, self.group, self.p_value ) candidates = [] at: ciphey.iface._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.ConfigurableModule getParams() -> Optional[Dict[str, ParamSpec]] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: ciphey.iface._modules class ParamSpec(NamedTuple): """ Attributes: req Whether this argument is required desc A description of what this argument does default The default value for this argument. Ignored if req == True or configPath is not None config_ref The path to the config that should be the default value list Whether this parameter is in the form of a list, and can therefore be specified more than once visible Whether the user can tweak this via the command line """ req: bool desc: str default: Optional[Any] = None list: bool = False config_ref: Optional[List[str]] = None + visible: bool = True - visible: bool = False ===========changed ref 1=========== # module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): + def getInfo(self, ctext: str) -> CrackInfo: - def getInfo(self, ctext: T) -> CrackInfo: analysis = self.cache.get_or_update( ctext, "cipheycore::simple_analysis", lambda: cipheycore.analyse_string(ctext), ) return CrackInfo( success_likelihood=cipheycore.caesar_detect(analysis, self.expected), # TODO: actually calculate runtimes + success_runtime=1e-5, - success_runtime=1e-4, + failure_runtime=1e-5, - failure_runtime=1e-4, ) ===========changed ref 2=========== # module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: logger.debug("Trying caesar cipher") # Convert it to lower case # # TODO: handle different alphabets if self.lower: message = ctext.lower() else: message = ctext logger.trace("Beginning cipheycore simple analysis") # Hand it off to the core analysis = self.cache.get_or_update( ctext, "cipheycore::simple_analysis", + lambda: cipheycore.analyse_string(ctext), - lambda: cipheycore.analyse_string(message), ) logger.trace("Beginning cipheycore::caesar") possible_keys = cipheycore.caesar_crack( + analysis, self.expected, self.group, self.p_value - analysis, self.expected, self.group, True, self.p_value ) + n_candidates = len(possible_keys) logger.debug(f"Caesar returned {n_candidates} candidates") + + if n_candidates == 0: + logger.trace(f"Filtering for better results") + analysis = cipheycore.analyse_string(ctext, self.group) + possible_keys = cipheycore.caesar_crack( + analysis, self.expected, self.group, self.p_value + ) candidates = [] for candidate in possible_keys: + logger.trace(f"Candidate {candidate.key} has prob {candidate.p_value}") translated = cipheycore.caesar_decrypt(message, candidate.key, self.group) candidates.append(CrackResult(value=translated, key_info=candidate.key)) return candidates ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 8=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 9=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 11=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 12=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 13=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 14=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 16=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) +
ciphey.basemods.Decoders.octal/Octal.decode
Modified
Ciphey~Ciphey
730236da700fe792c6eb36ed1507e2ea2af865ac
Merge branch 'master' into segfaults
<16>:<add> return None
# module: ciphey.basemods.Decoders.octal @registry.register class Octal(ciphey.iface.Decoder[str, bytes]): def decode(self, text: str) -> Optional[bytes]: <0> """ <1> It takes an octal string and return a string <2> :octal_str: octal str like "110 145 154" <3> """ <4> str_converted = [] <5> octal_seq = text.split(" ") <6> if len(octal_seq) == 1: <7> # Concatted octal must be formed of octal triplets <8> if len(text) % 3 != 0: <9> return None <10> octal_seq = [text[i:i+3] for i in range(0, len(text), 3)] <11> logger.trace(f"Trying chunked octal {octal_seq}") <12> try: <13> for octal_char in octal_seq: <14> if len(octal_char) > 3: <15> logger.trace(f"Octal subseq too long") <16> n = int(octal_char, 8) <17> if n < 0: # n cannot be greater than 255, as we checked that with the earlier length check <18> logger.trace(f"Non octal char {octal_char}") <19> return None <20> str_converted.append(n) <21> <22> return bytes(str_converted) <23> # Catch bad octal chars <24> except ValueError: <25> return None <26>
===========unchanged ref 0=========== at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch + class DuplicateNode(Exception): + pass + ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): - @abstractmethod - def findBestNode(self, nodes: Set[Node]) -> Node: - pass - ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + def get_crackers_for(self, t: type): + return registry[Cracker[t]] + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class AuSearchSuccessful(Exception): + target: 'Node' + info: str + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def empty(self): return len(self._sorted_priorities) == 0 + return len(self._sorted_priorities) == 0 + ===========changed ref 5=========== # module: ciphey.iface._config class Cache: + def try_get(self, ctext: Any, keyname: str): + return self._cache[ctext].get(keyname) + ===========changed ref 6=========== # module: ciphey.iface._config class Config: + # Setter methods for cleaner library API + def set_verbosity(self, i): + self.update_log_level(i) + return self + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def __init__(self): + self._sorted_priorities = [] + self._queues = {} + ===========changed ref 8=========== # module: ciphey.iface._config class Cache: + def __init__(self): + self._cache: Dict[Any, Dict[str, Any]] = {} + ===========changed ref 9=========== # module: ciphey.iface._modules class SearchLevel(NamedTuple): + @staticmethod + def input(ctext: Any): + return SearchLevel(name="input", result=CrackResult(ctext)) + ===========changed ref 10=========== # module: ciphey if __name__ == '__main__': + main() - ciphey.main() ===========changed ref 11=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): - def __hash__(self): - return hash((type(self.cracker).__name__, len(self.parents))) - ===========changed ref 13=========== # module: ciphey.iface._config class Config: + @staticmethod + def library_default(): + """The default config for use in a library""" + return Config().set_verbosity(-1) + ===========changed ref 14=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + _sorted_priorities: List[PriorityType] + _queues: Dict[Any, List[T]] + ===========changed ref 15=========== # module: ciphey.basemods.Searchers.ausearch + def convert_edge_info(info: CrackInfo): + return cipheycore.ausearch_edge(info.success_likelihood, info.success_runtime, info.failure_runtime) + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + def get_path(self): + if self.parent is None: + return [self.level] + return self.parent.source.get_path() + [self.level] + ===========changed ref 17=========== # module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): - checkers: List[Checker[str]] = [] - """ This object is effectively a prebuilt quroum (with requirement 1) of common patterns """ ===========changed ref 18=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work_chunk(self) -> List[T]: + """Returns the best work for now""" + best_priority = self._sorted_priorities.pop(0) + return self._queues.pop(best_priority) + ===========changed ref 19=========== # module: tests.test_main + def test_plaintext(): + res = decrypt(Config.library_default().complete_config(), answer_str) + + print(res) + + assert res.lower() == answer_str.lower() + ===========changed ref 20=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Node: - class Node(Generic[T], NamedTuple): + @staticmethod + def root(config: Config, ctext: Any): + if not config.cache.mark_ctext(ctext): + raise DuplicateNode() + + return Node(parent=None, level=SearchLevel.input(ctext)) + ===========changed ref 21=========== # module: ciphey.iface._config class Cache: """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions""" - _cache: Dict[Any, Dict[str, Any]] = {} - ===========changed ref 22=========== # module: ciphey.basemods.Searchers.ausearch + @registry.register + class AuSearch(Searcher): - class AuSearch(Searcher, ABC): + @lru_cache() # To save extra sorting + def get_decoders_for(self, t: type): + ret = [j for i in registry[Decoder][t].values() for j in i] + ret.sort(key=lambda x: x.priority(), reverse=True) + return ret + ===========changed ref 23=========== # module: ciphey.basemods.Searchers.ausearch + """ + We are using a tree structure here, because that makes searching and tracing back easier + + As such, when we encounter another possible parent, we remove that edge + """ + + PriorityType = TypeVar('PriorityType') ===========changed ref 24=========== # module: ciphey.iface._config class Config: - # Does all the loading and filling - + def complete_config(self) -> 'Config': - def complete_config(self): + """This does all the loading for the config, and then returns itself""" self.load_modules() self.load_objs() self.update_log_level(self.verbosity) + return self ===========changed ref 25=========== + # module: tools.freq_analysis + data = sys.stdin.read() + + analysis = cipheycore.analyse_string(data) + + print(json.dumps({i: j / len(data) for i, j in analysis.freqs.items()})) + ===========changed ref 26=========== # module: ciphey.basemods.Searchers.ausearch + @dataclass + class Edge: + source: Node + route: Union[Cracker, Decoder] + dest: Optional[Node] = None + # Info is not filled in for Decoders + info: Optional[cipheycore.ausearch_edge] = None + ===========changed ref 27=========== # module: ciphey.basemods.Searchers.ausearch + class PriorityWorkQueue(Generic[PriorityType, T]): + def get_work(self) -> T: + best_priority = self._sorted_priorities[0] + target = self._queues[best_priority] + ret = target.pop(0) + if len(target) == 0: + self._sorted_priorities.pop() + return ret +
ciphey.ciphey/main
Modified
Ciphey~Ciphey
4c11912933af33aa540ffd3de1dd980f80a1f04d
Made importing nicer
<s>Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) + def main(**kwargs): - def main(**kwargs) -> Optional[dict]: <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if "appdirs" in kwargs and kwargs["appdirs"]: <32> dirs = AppDirs("Ciphey", "Ciph</s>
===========below chunk 0=========== <s>=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) + def main(**kwargs): - def main(**kwargs) -> Optional[dict]: # offset: 1 path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") #</s> ===========below chunk 1=========== <s>=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) + def main(**kwargs): - def main(**kwargs) -> Optional[dict]: # offset: 2 <s>) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") </s> ===========below chunk 2=========== <s>=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) + def main(**kwargs): - def main(**kwargs) -> Optional[dict]: # offset: 3 <s> kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug or quiet mode is on, run without spinner if config.verbosity != 0: result = decrypt(config, kwargs["text"]) else: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth) as sp: result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result) return result ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.ciphey/main
Modified
Ciphey~Ciphey
c19e1acf93de7381821b65e973f8c5a07966fdaf
Made spinner more friendly
<s>Adds a module from the given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if "appdirs" in kwargs and kwargs["appdirs"]: <32> dirs = AppDirs("Ciphey", "Ciph</s>
===========below chunk 0=========== <s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 1 path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") #</s> ===========below chunk 1=========== <s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 2 <s>) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") </s> ===========below chunk 2=========== <s> given path", type=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag = True, ) @click.argument("text_stdin", callback=get_name, required=False) @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 3 <s> kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None # if debug or quiet mode is on, run without spinner if config.verbosity != 0: result = decrypt(config, kwargs["text"]) else: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth) as sp: result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result) ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.basemods.Searchers.ausearch/PriorityWorkQueue.get_work_chunk
Modified
Ciphey~Ciphey
23c90d4daf8d92444f081ff4c6236c465796e6d0
Merge branch 'master' of github.com:Ciphey/Ciphey into master
<1>:<add> if len(self._sorted_priorities) == 0: <add> return []
# module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def get_work_chunk(self) -> List[T]: <0> """Returns the best work for now""" <1> best_priority = self._sorted_priorities.pop(0) <2> return self._queues.pop(best_priority) <3>
ciphey.basemods.Searchers.ausearch/AuSearch.search
Modified
Ciphey~Ciphey
23c90d4daf8d92444f081ff4c6236c465796e6d0
Merge branch 'master' of github.com:Ciphey/Ciphey into master
<23>:<add> if self.disable_priority: <add> chunk += self.work.get_work_chunk() <add> infos = [i.info for i in chunk] <add>
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: <0> logger.trace(f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""") <1> <2> try: <3> root = Node.root(self._config(), ctext) <4> except DuplicateNode: <5> return None <6> <7> if type(ctext) == self._config().objs["format"]["out"]: <8> check_res = self._config().objs["checker"](ctext) <9> if check_res is not None: <10> return SearchResult(check_res=check_res, path=[root.level]) <11> <12> try: <13> self.recursive_expand(root) <14> <15> while True: <16> if self.work.empty(): <17> break <18> # Get the highest level result <19> chunk = self.work.get_work_chunk() <20> infos = [i.info for i in chunk] <21> # Work through all of this level's results <22> while len(chunk) != 0: <23> logger.trace(f"{len(infos)} remaining on this level") <24> step_res = cipheycore.ausearch_minimise(infos) <25> edge: Edge = chunk.pop(step_res.index) <26> logger.trace(f"Weight is currently {step_res.weight} " <27> f"when we pick {type(edge.route).__name__.lower()}") <28> del infos[step_res.index] <29> <30> # Expand the node <31> res = edge.route(edge.source.level.result.value) <32> if res is None: <33> continue <34> for i in res: <35> try: <36> node = Node.cracker(config=self._config(), edge_template=edge, result=i) <37> self.recursive_expand(node) <38> except DuplicateNode: <39> continue <40> <41> except AuSearch</s>
===========below chunk 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 logger.debug("AuSearch succeeded") return SearchResult(path=e.target.get_path(), check_res=e.info) logger.debug("AuSearch failed") ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def get_work_chunk(self) -> List[T]: """Returns the best work for now""" + if len(self._sorted_priorities) == 0: + return [] best_priority = self._sorted_priorities.pop(0) return self._queues.pop(best_priority)
ciphey.ciphey/main
Modified
Ciphey~Ciphey
01f8aa1e6ea1eba13c91528b90635336137b657e
Hopefully fixed windows ci
<s>iphey wants the settings file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if "appdirs" in kwargs and kwargs["appdirs"]: <32> dirs = AppDirs("Ciphey", "Ciph</s>
===========below chunk 0=========== <s> file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 1 path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") #</s> ===========below chunk 1=========== <s> file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 2 <s>) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file_stdin"] is not None: kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") </s> ===========below chunk 2=========== <s> file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 3 <s> kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None result: Optional[str] # if debug or quiet mode is on, run without spinner if config.verbosity != 0: result = decrypt(config, kwargs["text"]) else: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, "Thinking") as sp: result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result) ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
noxfile/safety
Modified
Ciphey~Ciphey
01f8aa1e6ea1eba13c91528b90635336137b657e
Hopefully fixed windows ci
<0>:<del> with tempfile.NamedTemporaryFile() as requirements: <1>:<add> session.run( <del> session.run( <2>:<add> "poetry", <del> "poetry", <3>:<add> "export", <del> "export", <4>:<add> "--dev", <del> "--dev", <5>:<add> "--format=requirements.txt", <del> "--format=requirements.txt", <6>:<add> "--without-hashes", <del> "--without-hashes", <7>:<add> f"--output=requirements.txt", <del> f"--output={requirements.name}", <8>:<add> external=True, <del> external=True, <9>:<add> ) <del> ) <10>:<add> install_with_constraints(session, "safety") <del> install_with_constraints(session, "safety") <11>:<add> session.run("safety", "check", f"--file={requirements.name}", "--full-report") <del> session.run("safety", "check", f"--file={requirements.name}", "--full-report")
# module: noxfile @nox.session def safety(session): <0> with tempfile.NamedTemporaryFile() as requirements: <1> session.run( <2> "poetry", <3> "export", <4> "--dev", <5> "--format=requirements.txt", <6> "--without-hashes", <7> f"--output={requirements.name}", <8> external=True, <9> ) <10> install_with_constraints(session, "safety") <11> session.run("safety", "check", f"--file={requirements.name}", "--full-report") <12>
===========unchanged ref 0=========== at: noxfile install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None ===========changed ref 0=========== <s>iphey wants the settings file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): """Ciphey - Automated Decryption Tool Documentation: https://docs.ciphey.online\n Discord (support here, we're online most of the day): https://discord.ciphey.online/\n GitHub: https://github.com/ciphey/ciphey\n Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. Examples:\n Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" """ """Function to deal with arguments. Either calls with args or not. Makes Pytest work. It gets the arguments in the function definition using locals() if withArgs is True, that means this is being called with command line args so go to arg_parsing() to get those args we then update locals() with the new command line args and remove "withArgs" This function then calls call_encryption(**result) which passes our dict of args to the function as its own arguments using dict unpacking. Returns: The output of the decryption. """ # if user wants to know where appdirs is # print and exit if "appdirs" in kwargs and kwargs["appdirs"]: dirs = AppDirs("Ciphey", "Ciphey") path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os</s> ===========changed ref 1=========== <s> file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 1 <s> path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config</s> ===========changed ref 2=========== <s> file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 2 <s>osity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: + if kwargs["file"] is not None: - if kwargs["file_stdin"] is not None: + kwargs["text"] = kwargs</s> ===========changed ref 3=========== <s> file to be", type=bool, + is_flag=True, - is_flag = True, + ) + @click.option( + "-f", + "--file", + type=click.File("rb"), + required=False ) @click.argument("text_stdin", callback=get_name, required=False) - @click.argument("file_stdin", type=click.File("rb"), required=False) def main(**kwargs): # offset: 3 <s>"].read() + if config.objs["format"] != bytes: + kwargs["text"] = kwargs["text"].decode("utf-8") - kwargs["text"] = kwargs["file_stdin"].read().decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None result: Optional[str] # if debug or quiet mode is on, run without spinner if config.verbosity != 0: result = decrypt(config, kwargs["text"]) else: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, "Thinking") as sp: result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result)
noxfile/install_with_constraints
Modified
Ciphey~Ciphey
06624431456be7a6e0860d1999f44df788d00038
I *will* test before I commit
<12>:<del> with tempfile.NamedTemporaryFile() as requirements: <13>:<add> session.run( <del> session.run( <14>:<add> "poetry", <del> "poetry", <15>:<add> "export", <del> "export", <16>:<add> "--dev", <del> "--dev", <17>:<add> "--format=requirements.txt", <del> "--format=requirements.txt", <18>:<add> "--output=requirements.txt", <del> f"--output={requirements.name}", <19>:<add> external=True, <del> external=True, <20>:<add> ) <del> ) <21>:<add> session.install("--constraint=requirements.txt", *args, **kwargs) <del> session.install(f"--constraint={requirements.name}", *args, **kwargs)
# module: noxfile def install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None: <0> """Install packages constrained by Poetry's lock file. <1> This function is a wrapper for nox.sessions.Session.install. It <2> invokes pip to install packages inside of the session's virtualenv. <3> Additionally, pip is passed a constraints file generated from <4> Poetry's lock file, to ensure that the packages are pinned to the <5> versions specified in poetry.lock. This allows you to manage the <6> packages as Poetry development dependencies. <7> Arguments: <8> session: The Session object. <9> args: Command-line arguments for pip. <10> kwargs: Additional keyword arguments for Session.install. <11> """ <12> with tempfile.NamedTemporaryFile() as requirements: <13> session.run( <14> "poetry", <15> "export", <16> "--dev", <17> "--format=requirements.txt", <18> f"--output={requirements.name}", <19> external=True, <20> ) <21> session.install(f"--constraint={requirements.name}", *args, **kwargs) <22>
noxfile/safety
Modified
Ciphey~Ciphey
06624431456be7a6e0860d1999f44df788d00038
I *will* test before I commit
<6>:<add> "--output=requirements.txt", <del> f"--output=requirements.txt", <10>:<add> session.run("safety", "check", "--file=requirements.txt", "--full-report") <del> session.run("safety", "check", f"--file={requirements.name}", "--full-report")
# module: noxfile @nox.session def safety(session): <0> session.run( <1> "poetry", <2> "export", <3> "--dev", <4> "--format=requirements.txt", <5> "--without-hashes", <6> f"--output=requirements.txt", <7> external=True, <8> ) <9> install_with_constraints(session, "safety") <10> session.run("safety", "check", f"--file={requirements.name}", "--full-report") <11>
===========unchanged ref 0=========== at: noxfile install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None ===========changed ref 0=========== # module: noxfile def install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None: """Install packages constrained by Poetry's lock file. This function is a wrapper for nox.sessions.Session.install. It invokes pip to install packages inside of the session's virtualenv. Additionally, pip is passed a constraints file generated from Poetry's lock file, to ensure that the packages are pinned to the versions specified in poetry.lock. This allows you to manage the packages as Poetry development dependencies. Arguments: session: The Session object. args: Command-line arguments for pip. kwargs: Additional keyword arguments for Session.install. """ - with tempfile.NamedTemporaryFile() as requirements: + session.run( - session.run( + "poetry", - "poetry", + "export", - "export", + "--dev", - "--dev", + "--format=requirements.txt", - "--format=requirements.txt", + "--output=requirements.txt", - f"--output={requirements.name}", + external=True, - external=True, + ) - ) + session.install("--constraint=requirements.txt", *args, **kwargs) - session.install(f"--constraint={requirements.name}", *args, **kwargs)
ciphey.mathsHelper/mathsHelper.strip_puncuation
Modified
Ciphey~Ciphey
30a3168c8c0b3f39bac1fe1a7333e62db3529c57
Merge branch 'master' into bee-remove-newline
<11>:<add> text: str = (str(text).translate(str.maketrans("", "", punctuation))).rstrip() <del> text: str = str(text).translate(str.maketrans("", "", punctuation))
# module: ciphey.mathsHelper class mathsHelper: @staticmethod def strip_puncuation(text: str) -> str: <0> """Strips punctuation from a given string. <1> <2> Uses string.puncuation. <3> <4> Args: <5> text -> the text to strip puncuation from. <6> <7> Returns: <8> Returns string without puncuation. <9> <10> """ <11> text: str = str(text).translate(str.maketrans("", "", punctuation)) <12> return text <13>
===========unchanged ref 0=========== at: string punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
ciphey.mathsHelper/mathsHelper.strip_puncuation
Modified
Ciphey~Ciphey
3eabcb107fe06cdb043f27b3250b99779f8139d2
Merge branch 'bee-remove-newline' of github.com:Ciphey/Ciphey into bee-remove-newline
<11>:<add> text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( <del> text: str = (str(text).translate(str.maketrans("", "", punctuation))).rstrip() <12>:<add> "\n" <add> )
# module: ciphey.mathsHelper class mathsHelper: @staticmethod def strip_puncuation(text: str) -> str: <0> """Strips punctuation from a given string. <1> <2> Uses string.puncuation. <3> <4> Args: <5> text -> the text to strip puncuation from. <6> <7> Returns: <8> Returns string without puncuation. <9> <10> """ <11> text: str = (str(text).translate(str.maketrans("", "", punctuation))).rstrip() <12> return text <13>
===========unchanged ref 0=========== at: string punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
ciphey.basemods.Decoders.atbash/Atbash.decode
Modified
Ciphey~Ciphey
898e81d2cb98555caed4c83198329ea3b9576329
Improve readability
<19>:<add> for letter in ctext: <del> for l in ctext: <20>:<add> if letter in atbash_dict.keys(): <del> if l in atbash_dict.keys(): <22>:<add> dec += atbash_dict[letter] <del> dec += atbash_dict[l] <26>:<add> dec += letter <del> dec += l
# module: ciphey.basemods.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Takes an encoded string and attempts to decode it according to the Atbash cipher. <2> <3> The Atbash cipher is a very simple substitution cipher without a key. <4> It operates by replacing every letter in the input by its 'counterpoint' <5> in the alphabet. Example: A -> Z, B -> Y, ... , M -> N and vice versa. <6> """ <7> <8> dec = "" <9> letters = list("abcdefghijklmnopqrstuvwxyz") <10> atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)} <11> <12> # Ensure that ciphertext is a string <13> if type(ctext) == str: <14> # Normalize the string to all-lowercase letters <15> ctext = ctext.lower() <16> else: <17> return None <18> <19> for l in ctext: <20> if l in atbash_dict.keys(): <21> # Match every letter of the input to its atbash counterpoint <22> dec += atbash_dict[l] <23> else: <24> # If the current character is not in the defined alphabet, <25> # just accept it as-is (useful for numbers, punctuation,...) <26> dec += l <27> return dec <28>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U]
ciphey.basemods.Decoders.atbash/Atbash.decode
Modified
Ciphey~Ciphey
7f612a95c20242f46ddd4c1aa4cd73d66dda46d6
Improve readability
<8>:<add> result = "" <del> dec = "" <22>:<add> result += atbash_dict[letter] <del> dec += atbash_dict[letter] <26>:<add> result += letter <del> dec += letter <27>:<add> return result <del> return dec
# module: ciphey.basemods.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Takes an encoded string and attempts to decode it according to the Atbash cipher. <2> <3> The Atbash cipher is a very simple substitution cipher without a key. <4> It operates by replacing every letter in the input by its 'counterpoint' <5> in the alphabet. Example: A -> Z, B -> Y, ... , M -> N and vice versa. <6> """ <7> <8> dec = "" <9> letters = list("abcdefghijklmnopqrstuvwxyz") <10> atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)} <11> <12> # Ensure that ciphertext is a string <13> if type(ctext) == str: <14> # Normalize the string to all-lowercase letters <15> ctext = ctext.lower() <16> else: <17> return None <18> <19> for letter in ctext: <20> if letter in atbash_dict.keys(): <21> # Match every letter of the input to its atbash counterpoint <22> dec += atbash_dict[letter] <23> else: <24> # If the current character is not in the defined alphabet, <25> # just accept it as-is (useful for numbers, punctuation,...) <26> dec += letter <27> return dec <28>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U]
ciphey.ciphey/main
Modified
Ciphey~Ciphey
3914dfe753dceb71382853f3109bc4cc0955dc15
Merge branch 'master' into patch-1
<s>=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if "appdirs" in kwargs and kwargs["appdirs"]: <32> dirs = AppDirs("Ciphey", "Ciph</s>
===========below chunk 0=========== <s> multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 1 path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Default init the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") #</s> ===========below chunk 1=========== <s> multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 2 <s>) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("in", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file"] is not None: kwargs["text"] = kwargs["file"].read() if config.objs["format"] != bytes</s> ===========below chunk 2=========== <s> multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 3 <s> kwargs["text"] = kwargs["text"].decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None result: Optional[str] # if debug or quiet mode is on, run without spinner if config.verbosity != 0: result = decrypt(config, kwargs["text"]) else: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, "Thinking") as sp: result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result) ===========unchanged ref 0=========== at: ciphey.ciphey get_name(ctx, param, value) at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
ciphey.basemods.Crackers.XandY/XandY.getInfo
Modified
Ciphey~Ciphey
c79ef4535f65537b75f36344253bb78bfac21e79
Merge branch 'master' of https://github.com/lukasgabriel/Ciphey
<1>:<add> success_likelihood=0.1, success_runtime=1e-5, failure_runtime=1e-5, <del> success_likelihood=0.5, success_runtime=1e-5, failure_runtime=1e-5,
# module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: <0> return CrackInfo( <1> success_likelihood=0.5, success_runtime=1e-5, failure_runtime=1e-5, <2> ) <3>
===========unchanged ref 0=========== at: ciphey.iface._modules CrackInfo(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker getInfo(self, ctext: T) -> CrackInfo
ciphey.basemods.Decoders.galactic/Galactic.decode
Modified
Ciphey~Ciphey
816a602420f0925a3f9f9c355ffddf7c3dfa00dd
Fix complication in galactic decoder
<4>:<add> logger.trace("Attempting Standard Galactic Alphabet Decoder") <5>:<add> # To avoid complications, only move forward with the decoding if we can <add> # reasonably assume that the input string is written in the galactic alphabet <add> galactic_matches = 0 <add> for symbol in self.GALACTIC_DICT.keys(): <add> # These symbols are assumed to be frequent enough in regular <add> # text to be skipped when counting the matches. All others are counted. <add> if symbol in ctext and symbol not in ["!", "|"]: <add> galactic_matches += 1 <add> else: <add> continue <add> if galactic_matches == 0: <add> logger.trace( <add> "No matching galactic alphabet letters found. Skipping galactic decoder..." <add> ) <add> return None <add> logger.trace(f"{galactic_matches} galactic alphabet letters found. ") <add> <del> logger.trace("Attempting Standard Galactic Alphabet Decoder") <28>:<del> # TODO: Handle edge cases where x still does not show up
# module: ciphey.basemods.Decoders.galactic @registry.register class Galactic(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Takes a string written in the 'Standard Galactic Alphabet' <2> (aka Minecraft Enchanting Table Symbols) and translates it to ASCII text. <3> """ <4> <5> logger.trace("Attempting Standard Galactic Alphabet Decoder") <6> result = "" <7> ctext = ( <8> ctext.replace("||", "|") <9> .replace("/", "") <10> .replace("¡", "") <11> .replace(" ̣ ", "") <12> .replace(" ̇", " x") <13> ) <14> logger.trace(f"Modified string is {ctext}") <15> # Take out the problematic characters consisting of multiple symbols <16> for letter in ctext: <17> if letter in self.GALACTIC_DICT.keys(): <18> # Match every letter of the input to its galactic counterpoint <19> result += self.GALACTIC_DICT[letter] <20> else: <21> # If the current character is not in the defined alphabet, <22> # just accept it as-is (useful for numbers, punctuation,...) <23> result += letter <24> <25> result = result.replace("x ", "x") <26> # Remove the trailing space (appearing as a leading space) <27> # from the x that results from the diacritic replacement <28> # TODO: Handle edge cases where x still does not show up <29> logger.trace(f"Decoded string is {result}") <30> return result <31>
===========unchanged ref 0=========== at: ciphey.basemods.Decoders.galactic.Galactic.__init__ self.GALACTIC_DICT = config.get_resource(self._params()["dict"], WordList) at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") Decoder(config: Config) at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U]
ciphey.iface._modules/pretty_search_results
Modified
Ciphey~Ciphey
0f7abb05cef38425e9f0b5f68cde3e8a566b9018
Merge branch 'master' into bee-fix-old-green
<35>:<add> f"""\nFinal result: [bold green]"{res.path[-1].result.value}"[bold green]""" <del> f"""\nFinal result: [bold green]"{res.path[-1].result.value}"[\bold green]"""
# module: ciphey.iface._modules def pretty_search_results(res: SearchResult, display_intermediate: bool = False) -> str: <0> ret: str = "" <1> if len(res.check_res) != 0: <2> ret += f"Checker: {res.check_res}\n" <3> ret += "Format used:\n" <4> <5> def add_one(): <6> nonlocal ret <7> ret += f" {i.name}" <8> already_broken = False <9> if i.result.key_info is not None: <10> ret += f":\n Key: {i.result.key_info}\n" <11> already_broken = True <12> if i.result.misc_info is not None: <13> if not already_broken: <14> ret += ":\n" <15> ret += f" Misc: {i.result.misc_info}\n" <16> already_broken = True <17> if display_intermediate: <18> if not already_broken: <19> ret += ":\n" <20> ret += f' Value: "{i.result.value}"\n' <21> already_broken = True <22> if not already_broken: <23> ret += "\n" <24> <25> # Skip the 'input' and print in order <26> for i in res.path[1:]: <27> add_one() <28> <29> # Remove trailing newline <30> ret = ret[:-1] <31> <32> # If we didn't show intermediate steps, then print the final result <33> if not display_intermediate: <34> ret += ( <35> f"""\nFinal result: [bold green]"{res.path[-1].result.value}"[\bold green]""" <36> ) <37> <38> return ret <39>
===========unchanged ref 0=========== at: ciphey.iface._modules SearchResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.CrackResult value: T key_info: Optional[str] = None misc_info: Optional[str] = None at: ciphey.iface._modules.SearchLevel name: str result: CrackResult at: ciphey.iface._modules.SearchResult path: List[SearchLevel] check_res: str
ciphey.ciphey/main
Modified
Ciphey~Ciphey
0f7abb05cef38425e9f0b5f68cde3e8a566b9018
Merge branch 'master' into bee-fix-old-green
<s>=click.Path(), multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): <0> """Ciphey - Automated Decryption Tool <1> <2> Documentation: <3> https://docs.ciphey.online\n <4> Discord (support here, we're online most of the day): <5> https://discord.ciphey.online/\n <6> GitHub: <7> https://github.com/ciphey/ciphey\n <8> <9> Ciphey is an automated decryption tool using smart artificial intelligence and natural language processing. Input encrypted text, get the decrypted text back. <10> <11> Examples:\n <12> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13> <14> """ <15> <16> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <17> <18> It gets the arguments in the function definition using locals() <19> if withArgs is True, that means this is being called with command line args <20> so go to arg_parsing() to get those args <21> we then update locals() with the new command line args and remove "withArgs" <22> This function then calls call_encryption(**result) which passes our dict of args <23> to the function as its own arguments using dict unpacking. <24> <25> Returns: <26> The output of the decryption. <27> """ <28> <29> # if user wants to know where appdirs is <30> # print and exit <31> if "appdirs" in kwargs and kwargs["appdirs"]: <32> dirs = AppDirs("Ciphey", "Ciph</s>
===========below chunk 0=========== <s> multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 1 path_to_config = dirs.user_config_dir print(f"The settings.yml file should be at {os.path.join(path_to_config, 'settings.yml')}") return None # Now we create the config object config = iface.Config() # Load the settings file into the config load_msg: str cfg_arg = kwargs["config"] if cfg_arg is None: # Make sure that the config dir actually exists os.makedirs(iface.Config.get_default_dir(), exist_ok=True) config.load_file(create=True) load_msg = f"Opened config file at {os.path.join(iface.Config.get_default_dir(), 'config.yml')}" else: config.load_file(cfg_arg) load_msg = f"Opened config file at {cfg_arg}" # Load the verbosity, so that we can start logging verbosity = kwargs["verbose"] quiet = kwargs["quiet"] if verbosity is None: if quiet is not None: verbosity = -quiet elif quiet is not None: verbosity -= quiet if kwargs["greppable"] is not None: verbosity -= 999 # Use the existing value as a base config.verbosity += verbosity config.update_log_level(config.verbosity) logger.debug(load_msg) logger.trace(f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] </s> ===========below chunk 1=========== <s> multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 2 <s>f"Got cmdline args {kwargs}") # Now we load the modules module_arg = kwargs["module"] if module_arg is not None: config.modules += list(module_arg) # We need to load formats BEFORE we instantiate objects if kwargs["bytes_input"] is not None: config.update_format("in", "bytes") if kwargs["bytes_output"] is not None: config.update_format("out", "bytes") # Next, load the objects params = kwargs["param"] if params is not None: for i in params: key, value = i.split("=", 1) parent, name = key.split(".", 1) config.update_param(parent, name, value) config.update("checker", kwargs["checker"]) config.update("searcher", kwargs["searcher"]) config.update("default_dist", kwargs["default_dist"]) config.complete_config() logger.trace(f"Command line opts: {kwargs}") logger.trace(f"Config finalised: {config}") # Finally, we load the plaintext if kwargs["text"] is None: if kwargs["file"] is not None: kwargs["text"] = kwargs["file"].read() if config.objs["format"] != bytes: kwargs["text"] = kwargs["text"].decode("utf-</s> ===========below chunk 2=========== <s> multiple=True, ) @click.option( "-A", "--appdirs", help="Print the location of where Ciphey wants the settings file to be", type=bool, is_flag=True, ) @click.option( "-f", "--file", type=click.File("rb"), required=False ) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 3 <s> elif kwargs["text_stdin"] is not None: kwargs["text"] = kwargs["text_stdin"] else: # else print help menu print("[bold red]Error. No inputs were given to Ciphey. [\bold red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() # print("No inputs were given to Ciphey. For usage, run ciphey --help") return None result: Optional[str] # if debug or quiet mode is on, run without spinner if config.verbosity != 0: result = decrypt(config, kwargs["text"]) else: # else, run with spinner if verbosity is 0 with yaspin(Spinners.earth, "Thinking") as sp: result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result) ===========changed ref 0=========== # module: ciphey.iface._modules def pretty_search_results(res: SearchResult, display_intermediate: bool = False) -> str: ret: str = "" if len(res.check_res) != 0: ret += f"Checker: {res.check_res}\n" ret += "Format used:\n" def add_one(): nonlocal ret ret += f" {i.name}" already_broken = False if i.result.key_info is not None: ret += f":\n Key: {i.result.key_info}\n" already_broken = True if i.result.misc_info is not None: if not already_broken: ret += ":\n" ret += f" Misc: {i.result.misc_info}\n" already_broken = True if display_intermediate: if not already_broken: ret += ":\n" ret += f' Value: "{i.result.value}"\n' already_broken = True if not already_broken: ret += "\n" # Skip the 'input' and print in order for i in res.path[1:]: add_one() # Remove trailing newline ret = ret[:-1] # If we didn't show intermediate steps, then print the final result if not display_intermediate: ret += ( + f"""\nFinal result: [bold green]"{res.path[-1].result.value}"[bold green]""" - f"""\nFinal result: [bold green]"{res.path[-1].result.value}"[\bold green]""" ) return ret
tests.enciphey/encipher_crypto.__init__
Modified
Ciphey~Ciphey
21754c28975febbd6dbbc74edd9d701795127614
Merge branch 'master' into lukas-add-encryptions
<14>:<add> self.morse_dict = dict(cipheydists.get_translate("morse")) <del> self.morse_dict = dict(cipheydists.get_charset("morse"))
# module: tests.enciphey class encipher_crypto: def __init__(self): <0> self.methods = [ <1> self.Base64, <2> self.Ascii, <3> self.Base16, <4> self.Base32, <5> self.Binary, <6> self.Hex, <7> self.MorseCode, <8> self.Reverse, <9> self.Vigenere, <10> self.base58_bitcoin, <11> self.base58_ripple, <12> self.b62, <13> ] <14> self.morse_dict = dict(cipheydists.get_charset("morse")) <15> self.letters = string.ascii_lowercase <16> self.group = cipheydists.get_charset("english")["lcase"] <17>
===========unchanged ref 0=========== at: string ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' at: tests.enciphey.encipher_crypto Base64(text: str) -> str Base32(text: str) -> str Base16(text: str) -> str Binary(text: str) -> str Ascii(text: str) -> str Hex(text: str) -> str MorseCode(text: str) -> str Reverse(text: str) -> str Vigenere(plaintext) base58_bitcoin(text: str) base58_ripple(text: str) b62(text: str) ===========changed ref 0=========== + # module: tests.lukas + + ===========changed ref 1=========== + # module: tests.lukas + class atbash_encode: + """ + Encodes an input string with the Atbash cipher. + """ + ===========changed ref 2=========== + # module: tests.lukas + class XY_encrypt: + def to_binary(self): + return " ".join(f"{ord(i):08b}" for i in self.text) + ===========changed ref 3=========== + # module: tests.lukas + class galactic_encode: + """ + (Attempts to) encode an input string with the Standard Galactic Alphabet. + """ + ===========changed ref 4=========== + # module: tests.lukas + class XY_encrypt: + def randomizer(self): + s = list(self.ctext) + for i in range(len(s) - 1): + while random.randrange(2): + s[i] = s[i] + " " + return "".join(s) + ===========changed ref 5=========== + # module: tests.lukas + class galactic_encode: + def encode(self): + for char in self.text: + if char in self.galactic_dict.keys(): + self.ctext += self.galactic_dict[char] + else: + self.ctext += char + return self.ctext + ===========changed ref 6=========== + # module: tests.lukas + class XY_encrypt: + def __init__( + self, + text: str, + flip: bool = bool(random.randint(0, 1)), + randomize: bool = True, + key: list = None, + ): + self.ASCII = list(chr(x).encode() for x in range(128)) + self.text = text.lower() + self.ctext = "" + self.flip = flip + self.randomize = randomize + self.key = key + ===========changed ref 7=========== + # module: tests.lukas + class galactic_encode: + def __init__(self, text: str): + self.text = text.lower() + self.ctext = "" + + imported = dict(cipheydists.get_translate("galactic")) + self.galactic_dict = {value: key for (key, value) in imported.items()} + ===========changed ref 8=========== + # module: tests.lukas + class atbash_encode: + def __init__(self, text: str): + self.text = text.lower() + self.letters = list("abcdefghijklmnopqrstuvwxyz") + self.atbash_dict = {self.letters[::-1][i]: self.letters[i] for i in range(26)} + self.ctext = "" + ===========changed ref 9=========== + # module: tests.lukas + class atbash_encode: + def encode(self): + for letter in self.text: + if letter in self.atbash_dict.keys(): + # Match every letter of the input to its atbash counterpoint + self.ctext += self.atbash_dict[letter] + else: + # If the current character is not in the defined alphabet, + # just accept it as-is (useful for numbers, punctuation,...) + self.ctext += letter + return self.ctext + ===========changed ref 10=========== + # module: tests.lukas + class XY_encrypt: + """ + Encrypts an input string using binary substitution (called XandY in Ciphey) in which + first, the input string is converted to its binary representation and then the 0s and 1s + of the binary string are replaced with any two characters. + - flip: Which of the two possible rotations of the substitute characters is used? + - randomize: If True, random spaces are inserted into the cstring, which Ciphey can handle. + - key: Which two characters are used to represent the 0s and 1s? + """ + ===========changed ref 11=========== + # module: tests.lukas + class XY_encrypt: + def encrypt(self): + self.ctext = self.to_binary().replace(" ", "") + + if self.key: + one, two = self.key[0], self.key[1] + else: + one, two = random.choice(self.ASCII), random.choice(self.ASCII) + + self.ctext = self.ctext.replace(str(int(self.flip)), one).replace( + str(int(not self.flip)), two + ) + self.ctext = self.randomizer() if self.randomize == True else self.ctext + + return self.ctext +
ciphey.basemods.Crackers.vigenere/Vigenere.__init__
Modified
Ciphey~Ciphey
c46b464059c65d09ca7fd3ad78805147a38f6ef3
Merge branch 'master' into num-params
<10>:<add> self.p_value = float(self._params()["p_value"]) <del> self.p_value = self._params()["p_value"]
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def __init__(self, config: ciphey.iface.Config): <0> super().__init__(config) <1> self.lower: Union[str, bool] = self._params()["lower"] <2> if type(self.lower) != bool: <3> self.lower = util.strtobool(self.lower) <4> self.group = list(self._params()["group"]) <5> self.expected = config.get_resource(self._params()["expected"]) <6> self.cache = config.cache <7> self.keysize = self._params().get("keysize") <8> if self.keysize is not None: <9> self.keysize = int(self.keysize) <10> self.p_value = self._params()["p_value"] <11> self.MAX_KEY_LENGTH = 16 <12>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._config.Config get_resource(res_name: str, t: Optional[Type]=None) -> Any at: ciphey.iface._config.Config.__init__ self.cache: Cache = Cache() at: ciphey.iface._modules.ConfigurableModule _params() at: ciphey.iface._modules.Cracker __init__(config: Config) __init__(self, config: Config) at: distutils.util strtobool(val: str) -> bool
ciphey.basemods.Crackers.caesar/Caesar.__init__
Modified
Ciphey~Ciphey
c46b464059c65d09ca7fd3ad78805147a38f6ef3
Merge branch 'master' into num-params
<7>:<add> self.p_value = float(self._params()["p_value"]) <del> self.p_value = self._params()["p_value"]
# module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): def __init__(self, config: ciphey.iface.Config): <0> super().__init__(config) <1> self.lower: Union[str, bool] = self._params()["lower"] <2> if type(self.lower) != bool: <3> self.lower = util.strtobool(self.lower) <4> self.group = list(self._params()["group"]) <5> self.expected = config.get_resource(self._params()["expected"]) <6> self.cache = config.cache <7> self.p_value = self._params()["p_value"] <8>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._config.Config get_resource(res_name: str, t: Optional[Type]=None) -> Any at: ciphey.iface._config.Config.__init__ self.cache: Cache = Cache() at: ciphey.iface._modules.ConfigurableModule _params() at: ciphey.iface._modules.Cracker __init__(config: Config) __init__(self, config: Config) at: distutils.util strtobool(val: str) -> bool ===========changed ref 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def __init__(self, config: ciphey.iface.Config): super().__init__(config) self.lower: Union[str, bool] = self._params()["lower"] if type(self.lower) != bool: self.lower = util.strtobool(self.lower) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.keysize = self._params().get("keysize") if self.keysize is not None: self.keysize = int(self.keysize) + self.p_value = float(self._params()["p_value"]) - self.p_value = self._params()["p_value"] self.MAX_KEY_LENGTH = 16
ciphey.basemods.Searchers.ausearch/AuSearch.expand_crackers
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<7>:<add> <add> priority = min(node.depth, self.priority_cap) <del> if self.disable_priority: <8>:<del> priority = 0 <9>:<add> if self.invert_priority: <del> elif self.invert_priority: <10>:<add> priority = -priority <del> priority = -node.depth <11>:<del> else: <12>:<del> priority = node.depth
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: <0> res = node.level.result.value <1> <2> additional_work = [] <3> <4> for i in self.get_crackers_for(type(res)): <5> inst = self._config()(i) <6> additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) <7> if self.disable_priority: <8> priority = 0 <9> elif self.invert_priority: <10> priority = -node.depth <11> else: <12> priority = node.depth <13> <14> self.work.add_work(priority, additional_work) <15>
ciphey.basemods.Searchers.ausearch/AuSearch.search
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<23>:<add> # if self.disable_priority: <del> if self.disable_priority: <24>:<add> # chunk += self.work.get_work_chunk() <del> chunk += self.work.get_work_chunk() <25>:<add> # infos = [i.info for i in chunk] <del> infos = [i.info for i in chunk]
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: <0> logger.trace(f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""") <1> <2> try: <3> root = Node.root(self._config(), ctext) <4> except DuplicateNode: <5> return None <6> <7> if type(ctext) == self._config().objs["format"]["out"]: <8> check_res = self._config().objs["checker"](ctext) <9> if check_res is not None: <10> return SearchResult(check_res=check_res, path=[root.level]) <11> <12> try: <13> self.recursive_expand(root) <14> <15> while True: <16> if self.work.empty(): <17> break <18> # Get the highest level result <19> chunk = self.work.get_work_chunk() <20> infos = [i.info for i in chunk] <21> # Work through all of this level's results <22> while len(chunk) != 0: <23> if self.disable_priority: <24> chunk += self.work.get_work_chunk() <25> infos = [i.info for i in chunk] <26> <27> logger.trace(f"{len(infos)} remaining on this level") <28> step_res = cipheycore.ausearch_minimise(infos) <29> edge: Edge = chunk.pop(step_res.index) <30> logger.trace(f"Weight is currently {step_res.weight} " <31> f"when we pick {type(edge.route).__name__.lower()}") <32> del infos[step_res.index] <33> <34> # Expand the node <35> res = edge.route(edge.source.level.result.value) <36> if res is None: <37> continue <38> for i in res: <39> try: <40> node = Node.cracker(config=self._config(),</s>
===========below chunk 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 self.recursive_expand(node) except DuplicateNode: continue except AuSearchSuccessful as e: logger.debug("AuSearch succeeded") return SearchResult(path=e.target.get_path(), check_res=e.info) logger.debug("AuSearch failed") ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work)
ciphey.basemods.Searchers.ausearch/AuSearch.__init__
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<5>:<add> self.priority_cap = int(self._params()["priority_cap"]) <del> self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"]))
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): <0> super().__init__(config) <1> self._checker: Checker = config.objs["checker"] <2> self._target_type: type = config.objs["format"]["out"] <3> self.work = PriorityWorkQueue() # Has to be defined here because of sharing <4> self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) <5> self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) <6>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: logger.trace(f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""") try: root = Node.root(self._config(), ctext) except DuplicateNode: return None if type(ctext) == self._config().objs["format"]["out"]: check_res = self._config().objs["checker"](ctext) if check_res is not None: return SearchResult(check_res=check_res, path=[root.level]) try: self.recursive_expand(root) while True: if self.work.empty(): break # Get the highest level result chunk = self.work.get_work_chunk() infos = [i.info for i in chunk] # Work through all of this level's results while len(chunk) != 0: + # if self.disable_priority: - if self.disable_priority: + # chunk += self.work.get_work_chunk() - chunk += self.work.get_work_chunk() + # infos = [i.info for i in chunk] - infos = [i.info for i in chunk] logger.trace(f"{len(infos)} remaining on this level") step_res = cipheycore.ausearch_minimise(infos) edge: Edge = chunk.pop(step_res.index) logger.trace(f"Weight is currently {step_res.weight} " f"when we pick {type(edge.route).__name__.lower()}") del infos[step_res.index] # Expand the node res = edge.route(edge.source.level.result.value) if res is None: continue for i in res: try: node = Node.cracker(</s> ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s> if res is None: continue for i in res: try: node = Node.cracker(config=self._config(), edge_template=edge, result=i) self.recursive_expand(node) except DuplicateNode: continue except AuSearchSuccessful as e: logger.debug("AuSearch succeeded") return SearchResult(path=e.target.get_path(), check_res=e.info) logger.debug("AuSearch failed")
ciphey.basemods.Searchers.ausearch/AuSearch.getParams
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<4>:<del> default="False"), <5>:<del> "disable_priority": ParamSpec(req=False, <6>:<del> desc="Disables the priority queue altogether. " <7>:<del> "May be much faster, but will take *very* odd paths", <8>:<add> default="True"), <del> default="True") <9>:<add> "priority_cap": ParamSpec(req=False, <add> desc="Sets the maximum depth before we give up on the priority queue", <add> default="3")
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> return { <1> "invert_priority": ParamSpec(req=False, <2> desc="Causes more complex encodings to be looked at first. " <3> "Good for deeply buried encodings.", <4> default="False"), <5> "disable_priority": ParamSpec(req=False, <6> desc="Disables the priority queue altogether. " <7> "May be much faster, but will take *very* odd paths", <8> default="True") <9> } <10>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: logger.trace(f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""") try: root = Node.root(self._config(), ctext) except DuplicateNode: return None if type(ctext) == self._config().objs["format"]["out"]: check_res = self._config().objs["checker"](ctext) if check_res is not None: return SearchResult(check_res=check_res, path=[root.level]) try: self.recursive_expand(root) while True: if self.work.empty(): break # Get the highest level result chunk = self.work.get_work_chunk() infos = [i.info for i in chunk] # Work through all of this level's results while len(chunk) != 0: + # if self.disable_priority: - if self.disable_priority: + # chunk += self.work.get_work_chunk() - chunk += self.work.get_work_chunk() + # infos = [i.info for i in chunk] - infos = [i.info for i in chunk] logger.trace(f"{len(infos)} remaining on this level") step_res = cipheycore.ausearch_minimise(infos) edge: Edge = chunk.pop(step_res.index) logger.trace(f"Weight is currently {step_res.weight} " f"when we pick {type(edge.route).__name__.lower()}") del infos[step_res.index] # Expand the node res = edge.route(edge.source.level.result.value) if res is None: continue for i in res: try: node = Node.cracker(</s> ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s> if res is None: continue for i in res: try: node = Node.cracker(config=self._config(), edge_template=edge, result=i) self.recursive_expand(node) except DuplicateNode: continue except AuSearchSuccessful as e: logger.debug("AuSearch succeeded") return SearchResult(path=e.target.get_path(), check_res=e.info) logger.debug("AuSearch failed")
ciphey.basemods.Crackers.vigenere/Vigenere.getInfo
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<4>:<add> lambda: cipheycore.analyse_string(ctext.lower(), self.keysize, self.group), <del> lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), <17>:<add> lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), <del> lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value),
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: <0> if self.keysize is not None: <1> analysis = self.cache.get_or_update( <2> ctext, <3> f"vigenere::{self.keysize}", <4> lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), <5> ) <6> <7> return CrackInfo( <8> success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), <9> # TODO: actually calculate runtimes <10> success_runtime=1e-4, <11> failure_runtime=1e-4, <12> ) <13> <14> likely_lens = self.cache.get_or_update( <15> ctext, <16> f"vigenere::likely_lens", <17> lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value), <18> ) <19> <20> for keysize in likely_lens: <21> # Store the analysis <22> analysis = self.cache.get_or_update( <23> ctext, <24> f"vigenere::{keysize.len}", <25> lambda: keysize.tab <26> ) <27> if len(likely_lens) == 0: <28> return CrackInfo( <29> success_likelihood=0, <30> # TODO: actually calculate runtimes <31> success_runtime=2e-4, <32> failure_runtime=2e-4, <33> ) <34> <35> return CrackInfo( <36> success_likelihood=0*likely_lens[0].p_value, <37> # TODO: actually calculate runtimes <38> success_runtime=2e-4, <39> failure_runtime=2e-4, <40> ) <41>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.keysize = self._params().get("keysize") self.keysize = int(self.keysize) self.p_value = float(self._params()["p_value"]) at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) at: ciphey.iface._modules CrackInfo(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) Cracker(config: Config) at: ciphey.iface._modules.Cracker getInfo(self, ctext: T) -> CrackInfo ===========changed ref 0=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 1=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: logger.trace(f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""") try: root = Node.root(self._config(), ctext) except DuplicateNode: return None if type(ctext) == self._config().objs["format"]["out"]: check_res = self._config().objs["checker"](ctext) if check_res is not None: return SearchResult(check_res=check_res, path=[root.level]) try: self.recursive_expand(root) while True: if self.work.empty(): break # Get the highest level result chunk = self.work.get_work_chunk() infos = [i.info for i in chunk] # Work through all of this level's results while len(chunk) != 0: + # if self.disable_priority: - if self.disable_priority: + # chunk += self.work.get_work_chunk() - chunk += self.work.get_work_chunk() + # infos = [i.info for i in chunk] - infos = [i.info for i in chunk] logger.trace(f"{len(infos)} remaining on this level") step_res = cipheycore.ausearch_minimise(infos) edge: Edge = chunk.pop(step_res.index) logger.trace(f"Weight is currently {step_res.weight} " f"when we pick {type(edge.route).__name__.lower()}") del infos[step_res.index] # Expand the node res = edge.route(edge.source.level.result.value) if res is None: continue for i in res: try: node = Node.cracker(</s> ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s> if res is None: continue for i in res: try: node = Node.cracker(config=self._config(), edge_template=edge, result=i) self.recursive_expand(node) except DuplicateNode: continue except AuSearchSuccessful as e: logger.debug("AuSearch succeeded") return SearchResult(path=e.target.get_path(), check_res=e.info) logger.debug("AuSearch failed")
ciphey.basemods.Crackers.vigenere/Vigenere.crackOne
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<8>:<add> value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), <del> value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group),
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( + self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str - self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: <0> possible_keys = cipheycore.vigenere_crack( <1> analysis, self.expected, self.group, self.p_value <2> ) <3> logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") <4> # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: <5> # raise 0 <6> return [ <7> CrackResult( <8> value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), <9> key_info="".join([self.group[i] for i in candidate.key]), <10> ) <11> for candidate in possible_keys[:min(len(possible_keys), 10)] <12> ] <13>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.p_value = float(self._params()["p_value"]) at: ciphey.common fix_case(target: str, base: str) -> str at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: if self.keysize is not None: analysis = self.cache.get_or_update( ctext, f"vigenere::{self.keysize}", + lambda: cipheycore.analyse_string(ctext.lower(), self.keysize, self.group), - lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), ) return CrackInfo( success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes success_runtime=1e-4, failure_runtime=1e-4, ) likely_lens = self.cache.get_or_update( ctext, f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), - lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value), ) for keysize in likely_lens: # Store the analysis analysis = self.cache.get_or_update( ctext, f"vigenere::{keysize.len}", lambda: keysize.tab ) if len(likely_lens) == 0: return CrackInfo( success_likelihood=0, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) return CrackInfo( success_likelihood=0*likely_lens[0].p_value, # TODO: actually calculate runtimes success</s> ===========changed ref 2=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: # offset: 1 <s> success_likelihood=0*likely_lens[0].p_value, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) ===========changed ref 3=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work)
ciphey.basemods.Crackers.vigenere/Vigenere.attemptCrack
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<14>:<add> lambda: cipheycore.analyse_string(message, self.keysize, self.group), <del> lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), <16>:<add> ctext <22>:<add> lambda: cipheycore.vigenere_likely_key_lens(message, self.expected, self.group), <del> lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group), <35>:<add> lambda: cipheycore.analyse_string(message, i.len, self.group), <del> lambda: cipheycore.analyse_string(ctext, i.len, self.group), <37>:<add> ctext
# module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> logger.debug("Trying vigenere cipher") <1> # Convert it to lower case <2> if self.lower: <3> message = ctext.lower() <4> else: <5> message = ctext <6> <7> # Analysis must be done here, where we know the case for the cache <8> if self.keysize is not None: <9> return self.crackOne( <10> message, <11> self.cache.get_or_update( <12> ctext, <13> f"vigenere::{self.keysize}", <14> lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), <15> ), <16> ) <17> else: <18> arrs = [] <19> likely_lens = self.cache.get_or_update( <20> ctext, <21> f"vigenere::likely_lens", <22> lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group), <23> ) <24> possible_lens = [i for i in likely_lens] <25> possible_lens.sort(key=lambda i: i.p_value) <26> logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") <27> # TODO: work out length <28> for i in possible_lens: <29> arrs.extend( <30> self.crackOne( <31> message, <32> self.cache.get_or_update( <33> ctext, <34> f"vigenere::{i.len}", <35> lambda: cipheycore.analyse_string(ctext, i.len, self.group), <36> ), <37> ) <38> ) <39> <40> logger.debug(f"V</s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 return arrs ===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere crackOne(self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str) -> List[CrackResult] crackOne(ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str) -> List[CrackResult] at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.lower: Union[str, bool] = self._params()["lower"] self.lower = util.strtobool(self.lower) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.keysize = self._params().get("keysize") self.keysize = int(self.keysize) at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker attemptCrack(self, ctext: T) -> List[CrackResult] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( + self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str - self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: # raise 0 return [ CrackResult( + value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), - value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), key_info="".join([self.group[i] for i in candidate.key]), ) for candidate in possible_keys[:min(len(possible_keys), 10)] ] ===========changed ref 1=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: if self.keysize is not None: analysis = self.cache.get_or_update( ctext, f"vigenere::{self.keysize}", + lambda: cipheycore.analyse_string(ctext.lower(), self.keysize, self.group), - lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), ) return CrackInfo( success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes success_runtime=1e-4, failure_runtime=1e-4, ) likely_lens = self.cache.get_or_update( ctext, f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), - lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value), ) for keysize in likely_lens: # Store the analysis analysis = self.cache.get_or_update( ctext, f"vigenere::{keysize.len}", lambda: keysize.tab ) if len(likely_lens) == 0: return CrackInfo( success_likelihood=0, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) return CrackInfo( success_likelihood=0*likely_lens[0].p_value, # TODO: actually calculate runtimes success</s> ===========changed ref 2=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: # offset: 1 <s> success_likelihood=0*likely_lens[0].p_value, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) ===========changed ref 3=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 4=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"]))
ciphey.basemods.Decoders.atbash/Atbash.decode
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<12>:<del> # Ensure that ciphertext is a string <13>:<del> if type(ctext) == str: <14>:<del> # Normalize the string to all-lowercase letters <15>:<del> ctext = ctext.lower() <16>:<del> else: <17>:<del> return None <18>:<del> <19>:<add> for letter in ctext.lower(): <del> for letter in ctext: <27>:<add> return fix_case(result, ctext) <del> return result
# module: ciphey.basemods.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Takes an encoded string and attempts to decode it according to the Atbash cipher. <2> <3> The Atbash cipher is a very simple substitution cipher without a key. <4> It operates by replacing every letter in the input by its 'counterpoint' <5> in the alphabet. Example: A -> Z, B -> Y, ... , M -> N and vice versa. <6> """ <7> <8> result = "" <9> letters = list("abcdefghijklmnopqrstuvwxyz") <10> atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)} <11> <12> # Ensure that ciphertext is a string <13> if type(ctext) == str: <14> # Normalize the string to all-lowercase letters <15> ctext = ctext.lower() <16> else: <17> return None <18> <19> for letter in ctext: <20> if letter in atbash_dict.keys(): <21> # Match every letter of the input to its atbash counterpoint <22> result += atbash_dict[letter] <23> else: <24> # If the current character is not in the defined alphabet, <25> # just accept it as-is (useful for numbers, punctuation,...) <26> result += letter <27> return result <28>
===========unchanged ref 0=========== at: ciphey.common fix_case(target: str, base: str) -> str at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") Decoder(config: Config) at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] priority() -> float ===========changed ref 0=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 1=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 5=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( + self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str - self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: # raise 0 return [ CrackResult( + value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), - value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), key_info="".join([self.group[i] for i in candidate.key]), ) for candidate in possible_keys[:min(len(possible_keys), 10)] ] ===========changed ref 6=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: if self.keysize is not None: analysis = self.cache.get_or_update( ctext, f"vigenere::{self.keysize}", + lambda: cipheycore.analyse_string(ctext.lower(), self.keysize, self.group), - lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), ) return CrackInfo( success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes success_runtime=1e-4, failure_runtime=1e-4, ) likely_lens = self.cache.get_or_update( ctext, f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), - lambda: cipheycore.vigenere_likely_key_lens(ctext, self.expected, self.group, self.p_value), ) for keysize in likely_lens: # Store the analysis analysis = self.cache.get_or_update( ctext, f"vigenere::{keysize.len}", lambda: keysize.tab ) if len(likely_lens) == 0: return CrackInfo( success_likelihood=0, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) return CrackInfo( success_likelihood=0*likely_lens[0].p_value, # TODO: actually calculate runtimes success</s>
tests.test_main/test_plaintext
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<4>:<add> assert res == answer_str <del> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_plaintext(): <0> res = decrypt(Config.library_default().complete_config(), answer_str) <1> <2> print(res) <3> <4> assert res.lower() == answer_str.lower() <5>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config complete_config() -> 'Config' library_default() at: tests.test_main answer_str = "Hello my name is bee and I like dog and apple and tree" ===========changed ref 0=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 1=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 2=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 6=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( + self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str - self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: # raise 0 return [ CrackResult( + value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), - value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), key_info="".join([self.group[i] for i in candidate.key]), ) for candidate in possible_keys[:min(len(possible_keys), 10)] ] ===========changed ref 7=========== # module: ciphey.basemods.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: """ Takes an encoded string and attempts to decode it according to the Atbash cipher. The Atbash cipher is a very simple substitution cipher without a key. It operates by replacing every letter in the input by its 'counterpoint' in the alphabet. Example: A -> Z, B -> Y, ... , M -> N and vice versa. """ result = "" letters = list("abcdefghijklmnopqrstuvwxyz") atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)} - # Ensure that ciphertext is a string - if type(ctext) == str: - # Normalize the string to all-lowercase letters - ctext = ctext.lower() - else: - return None - + for letter in ctext.lower(): - for letter in ctext: if letter in atbash_dict.keys(): # Match every letter of the input to its atbash counterpoint result += atbash_dict[letter] else: # If the current character is not in the defined alphabet, # just accept it as-is (useful for numbers, punctuation,...) result += letter + return fix_case(result, ctext) - return result
tests.test_main/test_base64
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<5>:<add> assert res == answer_str <del> print(res) <7>:<del> assert res.lower() == answer_str.lower() <8>:<del>
# module: tests.test_main def test_base64(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", <3> ) <4> <5> print(res) <6> <7> assert res.lower() == answer_str.lower() <8>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config complete_config() -> 'Config' library_default() at: tests.test_main answer_str = "Hello my name is bee and I like dog and apple and tree" ===========changed ref 0=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 2=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 3=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 7=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( + self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str - self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: # raise 0 return [ CrackResult( + value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), - value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), key_info="".join([self.group[i] for i in candidate.key]), ) for candidate in possible_keys[:min(len(possible_keys), 10)] ] ===========changed ref 8=========== # module: ciphey.basemods.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: """ Takes an encoded string and attempts to decode it according to the Atbash cipher. The Atbash cipher is a very simple substitution cipher without a key. It operates by replacing every letter in the input by its 'counterpoint' in the alphabet. Example: A -> Z, B -> Y, ... , M -> N and vice versa. """ result = "" letters = list("abcdefghijklmnopqrstuvwxyz") atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)} - # Ensure that ciphertext is a string - if type(ctext) == str: - # Normalize the string to all-lowercase letters - ctext = ctext.lower() - else: - return None - + for letter in ctext.lower(): - for letter in ctext: if letter in atbash_dict.keys(): # Match every letter of the input to its atbash counterpoint result += atbash_dict[letter] else: # If the current character is not in the defined alphabet, # just accept it as-is (useful for numbers, punctuation,...) result += letter + return fix_case(result, ctext) - return result
tests.test_main/test_caesar
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<4>:<del> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_caesar(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", <3> ) <4> assert res.lower() == answer_str.lower() <5>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._config.Config complete_config() -> 'Config' library_default() at: tests.test_main answer_str = "Hello my name is bee and I like dog and apple and tree" at: tests.test_main.test_caesar res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) ===========changed ref 0=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 2=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 3=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 4=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 8=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( + self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str - self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: # raise 0 return [ CrackResult( + value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), - value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), key_info="".join([self.group[i] for i in candidate.key]), ) for candidate in possible_keys[:min(len(possible_keys), 10)] ]
tests.test_main/test_binary_base64_caesar
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<10>:<del> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_binary_base64_caesar(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " <3> "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " <4> "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " <5> "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " <6> "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " <7> "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " <8> "01000010 01101110 01011010 01011000 01001010 01111001 00001010", <9> ) <10> assert res.lower() == answer_str.lower() <11>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config complete_config() -> 'Config' library_default() at: tests.test_main answer_str = "Hello my name is bee and I like dog and apple and tree" ===========changed ref 0=========== # module: tests.test_main def test_caesar(): res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 3=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 4=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 5=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work) ===========changed ref 9=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( + self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str - self, ctext: str, analysis: cipheycore.windowed_analysis_res ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) logger.trace(f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}") # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: # raise 0 return [ CrackResult( + value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), - value=cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), key_info="".join([self.group[i] for i in candidate.key]), ) for candidate in possible_keys[:min(len(possible_keys), 10)] ]
tests.test_main/test_vigenere
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<4>:<del> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_vigenere(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic", <3> ) <4> assert res.lower() == answer_str.lower() <5>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config complete_config() -> 'Config' library_default() ===========changed ref 0=========== # module: tests.test_main def test_caesar(): res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 3=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 4=========== # module: tests.test_main def test_binary_base64_caesar(): res = decrypt( Config().library_default().complete_config(), "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " "01000010 01101110 01011010 01011000 01001010 01111001 00001010", ) - assert res.lower() == answer_str.lower() ===========changed ref 5=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 6=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work)
tests.test_main/test_binary
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<9>:<add> assert res == answer_str <del> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_binary(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 " <3> "01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 " <4> "01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 " <5> "01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100001 01110000 01110000 01101100 " <6> "01100101 00100000 01100001 01101110 01100100 00100000 01110100 01110010 01100101 01100101", <7> ) <8> <9> assert res.lower() == answer_str.lower() <10>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config complete_config() -> 'Config' library_default() ===========changed ref 0=========== # module: tests.test_main def test_vigenere(): res = decrypt( Config().library_default().complete_config(), "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic", ) - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main def test_caesar(): res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) - assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 3=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 4=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 5=========== # module: tests.test_main def test_binary_base64_caesar(): res = decrypt( Config().library_default().complete_config(), "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " "01000010 01101110 01011010 01011000 01001010 01111001 00001010", ) - assert res.lower() == answer_str.lower() ===========changed ref 6=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 7=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 8=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work)
tests.test_main/test_hex
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<6>:<add> assert res == answer_str <del> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_hex(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "48656c6c6f206d79206e616d652069732062656520616e642049206c696b6520646f6720616e64206170706c6520616e6420" <3> "74726565", <4> ) <5> <6> assert res.lower() == answer_str.lower() <7>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config library_default() ===========changed ref 0=========== # module: tests.test_main def test_vigenere(): res = decrypt( Config().library_default().complete_config(), "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic", ) - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main def test_caesar(): res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) - assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 3=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 4=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 5=========== # module: tests.test_main def test_binary(): res = decrypt( Config().library_default().complete_config(), "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 " "01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 " "01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 " "01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100001 01110000 01110000 01101100 " "01100101 00100000 01100001 01101110 01100100 00100000 01110100 01110010 01100101 01100101", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 6=========== # module: tests.test_main def test_binary_base64_caesar(): res = decrypt( Config().library_default().complete_config(), "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " "01000010 01101110 01011010 01011000 01001010 01111001 00001010", ) - assert res.lower() == answer_str.lower() ===========changed ref 7=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 8=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") }
tests.test_main/test_atbash
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<4>:<add> assert res == answer_str <del> assert res.lower() == answer_str.lower()
# module: tests.test_main def test_atbash(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "Svool nb mznv rh yvv zmw R orpv wlt zmw zkkov zmw givv", <3> ) <4> assert res.lower() == answer_str.lower() <5>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config library_default() ===========changed ref 0=========== # module: tests.test_main def test_vigenere(): res = decrypt( Config().library_default().complete_config(), "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic", ) - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main def test_caesar(): res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) - assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 3=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 4=========== # module: tests.test_main def test_hex(): res = decrypt( Config().library_default().complete_config(), "48656c6c6f206d79206e616d652069732062656520616e642049206c696b6520646f6720616e64206170706c6520616e6420" "74726565", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 5=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 6=========== # module: tests.test_main def test_binary(): res = decrypt( Config().library_default().complete_config(), "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 " "01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 " "01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 " "01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100001 01110000 01110000 01101100 " "01100101 00100000 01100001 01101110 01100100 00100000 01110100 01110010 01100101 01100101", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 7=========== # module: tests.test_main def test_binary_base64_caesar(): res = decrypt( Config().library_default().complete_config(), "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " "01000010 01101110 01011010 01011000 01001010 01111001 00001010", ) - assert res.lower() == answer_str.lower() ===========changed ref 8=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 9=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") }
tests.test_main/XandY
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<4>:<add> assert res == answer_str <del> assert res.lower() == answer_str.lower()
# module: tests.test_main def XandY(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "xDDxDxxx xDDxxDxD xDDxDDxx xDDxDDxx xDDxDDDD xxDxxxxx xDDxDDxD xDDDDxxD xxDxxxxx xDDxDDDx xDDxxxxD xDDxDDxD xDDxxDxD xxDxxxxx xDDxDxxD xDDDxxDD xxDxxxxx xDDxxxDx xDDxxDxD xDDxxDxD xxDxxxxx xDDxxxxD xDDxDDDx xDDxxDxx xxDxxxxx xDxxDxxD xxDxxxxx xDDxDDxx xDDxDxxD xDDxDxDD xDDxxDxD xxDxxxxx xDDxxDxx xDDxDDDD xDDxxDDD xxDxxxxx xDDxxxxD xDDxDDDx xDDxxDxx xxDxxxxx xDDxxxxD xDDDxxxx xDDDxxxx xDDxDDxx xDDxxDxD xxDxxxxx xDDxxxxD xDDxDDDx xDDxxDxx xxDxxxxx xDDDxDxx xDDDxxDx xDDxxDxD xDDxxDxD", <3> ) <4> assert res.lower() == answer_str.lower() <5>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config library_default() ===========changed ref 0=========== # module: tests.test_main def test_atbash(): res = decrypt( Config().library_default().complete_config(), "Svool nb mznv rh yvv zmw R orpv wlt zmw zkkov zmw givv", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 1=========== # module: tests.test_main def test_vigenere(): res = decrypt( Config().library_default().complete_config(), "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic", ) - assert res.lower() == answer_str.lower() ===========changed ref 2=========== # module: tests.test_main def test_caesar(): res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) - assert res.lower() == answer_str.lower() ===========changed ref 3=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 4=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 5=========== # module: tests.test_main def test_hex(): res = decrypt( Config().library_default().complete_config(), "48656c6c6f206d79206e616d652069732062656520616e642049206c696b6520646f6720616e64206170706c6520616e6420" "74726565", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 6=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 7=========== # module: tests.test_main def test_binary(): res = decrypt( Config().library_default().complete_config(), "01001000 01100101 01101100 01101100 01101111 00100000 01101101 01111001 00100000 01101110 01100001 " "01101101 01100101 00100000 01101001 01110011 00100000 01100010 01100101 01100101 00100000 01100001 " "01101110 01100100 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 " "01101111 01100111 00100000 01100001 01101110 01100100 00100000 01100001 01110000 01110000 01101100 " "01100101 00100000 01100001 01101110 01100100 00100000 01110100 01110010 01100101 01100101", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 8=========== # module: tests.test_main def test_binary_base64_caesar(): res = decrypt( Config().library_default().complete_config(), "01010110 01011000 01001010 00110101 01100101 01010111 01001001 01100111 01100101 01101101 01110111 " "01100111 01011001 01010111 00110101 00110110 01100011 01101001 01000010 00110010 01011010 01101001 " "01000010 01110110 01100011 01101110 01001001 01100111 01100010 01101101 01000110 01111000 01001001 " "01000110 01011001 01100111 01100101 01011000 01011010 00110100 01100011 01101001 01000010 01111000 " "01011001 01101110 01010001 01100111 01100010 01101101 01000110 01111000 01001001 01000111 00110101 " "01101010 01011001 00110011 01101100 01111001 01001001 01000111 00110101 01101000 01100011 01010011 " "01000010 01101110 01011010 01011000 01001010 01111001 00001010", ) - assert res.lower() == answer_str.lower() ===========changed ref 9=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 10=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"]))
ciphey.basemods.Crackers.caesar/Caesar.attemptCrack
Modified
Ciphey~Ciphey
320d7ac34ef334ed3a730e54aebd1637f955d7a6
Merge branch 'master' into case-preservation
<37>:<add> candidates.append(CrackResult(value=fix_case(translated, ctext), key_info=candidate.key)) <del> candidates.append(CrackResult(value=translated, key_info=candidate.key))
# module: ciphey.basemods.Crackers.caesar @registry.register class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> logger.debug("Trying caesar cipher") <1> # Convert it to lower case <2> # <3> # TODO: handle different alphabets <4> if self.lower: <5> message = ctext.lower() <6> else: <7> message = ctext <8> <9> logger.trace("Beginning cipheycore simple analysis") <10> <11> # Hand it off to the core <12> analysis = self.cache.get_or_update( <13> ctext, <14> "cipheycore::simple_analysis", <15> lambda: cipheycore.analyse_string(ctext), <16> ) <17> logger.trace("Beginning cipheycore::caesar") <18> possible_keys = cipheycore.caesar_crack( <19> analysis, self.expected, self.group, self.p_value <20> ) <21> <22> n_candidates = len(possible_keys) <23> logger.debug(f"Caesar returned {n_candidates} candidates") <24> <25> if n_candidates == 0: <26> logger.trace(f"Filtering for better results") <27> analysis = cipheycore.analyse_string(ctext, self.group) <28> possible_keys = cipheycore.caesar_crack( <29> analysis, self.expected, self.group, self.p_value <30> ) <31> <32> candidates = [] <33> <34> for candidate in possible_keys: <35> logger.trace(f"Candidate {candidate.key} has prob {candidate.p_value}") <36> translated = cipheycore.caesar_decrypt(message, candidate.key, self.group) <37> candidates.append(CrackResult(value=translated, key_info=candidate.key)) <38> <39> return candidates <40>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.caesar.Caesar.__init__ self.lower: Union[str, bool] = self._params()["lower"] self.lower = util.strtobool(self.lower) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) self.cache = config.cache self.p_value = float(self._params()["p_value"]) at: ciphey.common fix_case(target: str, base: str) -> str at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker attemptCrack(self, ctext: T) -> List[CrackResult] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.common + def fix_case(target: str, base: str) -> str: + """Returns the lower-case string target with the case of base""" + ret = ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + # print([base[i].isupper() for i in range(len(target))]) + # print(ret) + return ''.join([target[i].upper() if base[i].isupper() else target[i] for i in range(len(target))]) + ===========changed ref 1=========== # module: tests.test_main + answer_str = "Hello my name is bee and I like dog and apple and tree" - answer_str = "Hello my name is bee and I like dog and apple and tree".lower() ===========changed ref 2=========== # module: tests.test_main def test_plaintext(): res = decrypt(Config.library_default().complete_config(), answer_str) print(res) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 3=========== # module: tests.test_main def test_vigenere(): res = decrypt( Config().library_default().complete_config(), "Rijvs ki rywi gc fco eln M jsoc nse krb ktnvi yxh rbic", ) - assert res.lower() == answer_str.lower() ===========changed ref 4=========== # module: tests.test_main def test_caesar(): res = decrypt( Config().library_default().complete_config(), "Uryyb zl anzr vf orr naq V yvxr qbt naq nccyr naq gerr", ) - assert res.lower() == answer_str.lower() ===========changed ref 5=========== # module: tests.test_main def test_atbash(): res = decrypt( Config().library_default().complete_config(), "Svool nb mznv rh yvv zmw R orpv wlt zmw zkkov zmw givv", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 6=========== # module: ciphey.common - def cached_freq_analysis(ctext, config): - base = config.objs.setdefault("cached_freq_analysis", ctext) - res = base.get("cached_freq_analysis") - if res is not None: - return res - - base["cached_freq_analysis"] = cipheycore.analyse_string(ctext) - ===========changed ref 7=========== # module: tests.test_main def test_base64(): res = decrypt( Config().library_default().complete_config(), "SGVsbG8gbXkgbmFtZSBpcyBiZWUgYW5kIEkgbGlrZSBkb2cgYW5kIGFwcGxlIGFuZCB0cmVl", ) + assert res == answer_str - print(res) - assert res.lower() == answer_str.lower() - ===========changed ref 8=========== # module: tests.test_main def test_hex(): res = decrypt( Config().library_default().complete_config(), "48656c6c6f206d79206e616d652069732062656520616e642049206c696b6520646f6720616e64206170706c6520616e6420" "74726565", ) + assert res == answer_str - assert res.lower() == answer_str.lower() ===========changed ref 9=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def __init__(self, config: Config): super().__init__(config) self._checker: Checker = config.objs["checker"] self._target_type: type = config.objs["format"]["out"] self.work = PriorityWorkQueue() # Has to be defined here because of sharing self.invert_priority = bool(distutils.util.strtobool(self._params()["invert_priority"])) + self.priority_cap = int(self._params()["priority_cap"]) - self.disable_priority = bool(distutils.util.strtobool(self._params()["disable_priority"])) ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", - default="False"), - "disable_priority": ParamSpec(req=False, - desc="Disables the priority queue altogether. " - "May be much faster, but will take *very* odd paths", + default="True"), - default="True") + "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up on the priority queue", + default="3") } ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): # def expand(self, edge: Edge) -> List[Edge]: # """Evaluates the destination of the given, and adds its child edges to the pool""" # edge.dest = Node(parent=edge, level=edge.route(edge.source.level.result.value)) def expand_crackers(self, node: Node) -> None: res = node.level.result.value additional_work = [] for i in self.get_crackers_for(type(res)): inst = self._config()(i) additional_work.append(Edge(source=node, route=inst, info=convert_edge_info(inst.getInfo(res)))) + + priority = min(node.depth, self.priority_cap) - if self.disable_priority: - priority = 0 + if self.invert_priority: - elif self.invert_priority: + priority = -priority - priority = -node.depth - else: - priority = node.depth self.work.add_work(priority, additional_work)
tests.test_main/test_XandY
Modified
Ciphey~Ciphey
bbb807f456e0c47287e70ffadc2cc3e511fc5f3e
merged
<4>:<add> assert res.lower() == answer_str.lower() <del> assert res == answer_str
# module: tests.test_main def test_XandY(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "xDDxDxxx xDDxxDxD xDDxDDxx xDDxDDxx xDDxDDDD xxDxxxxx xDDxDDxD xDDDDxxD xxDxxxxx xDDxDDDx xDDxxxxD xDDxDDxD xDDxxDxD xxDxxxxx xDDxDxxD xDDDxxDD xxDxxxxx xDDxxxDx xDDxxDxD xDDxxDxD xxDxxxxx xDDxxxxD xDDxDDDx xDDxxDxx xxDxxxxx xDxxDxxD xxDxxxxx xDDxDDxx xDDxDxxD xDDxDxDD xDDxxDxD xxDxxxxx xDDxxDxx xDDxDDDD xDDxxDDD xxDxxxxx xDDxxxxD xDDxDDDx xDDxxDxx xxDxxxxx xDDxxxxD xDDDxxxx xDDDxxxx xDDxDDxx xDDxxDxD xxDxxxxx xDDxxxxD xDDxDDDx xDDxxDxx xxDxxxxx xDDDxDxx xDDDxxDx xDDxxDxD xDDxxDxD", <3> ) <4> assert res == answer_str <5>
===========unchanged ref 0=========== at: ciphey.ciphey decrypt(config: iface.Config, ctext: Any) -> Union[str, bytes] at: ciphey.iface._config Config() at: ciphey.iface._config.Config complete_config() -> "Config" library_default() at: tests.test_main answer_str = "Hello my name is bee and I like dog and apple and tree"
tests.lukas/XY_encrypt.__init__
Modified
Ciphey~Ciphey
9ad0058278f12f64f47b98411a9ead88831af640
Fix bug with ASCII table
<0>:<add> self.ASCII = list(chr(x) for x in range(32, 127)) <del> self.ASCII = list(chr(x).encode() for x in range(128))
# module: tests.lukas class XY_encrypt: def __init__( self, text: str, flip: bool = bool(random.randint(0, 1)), randomize: bool = True, key: list = None, ): <0> self.ASCII = list(chr(x).encode() for x in range(128)) <1> self.text = text.lower() <2> self.ctext = "" <3> self.flip = flip <4> self.randomize = randomize <5> self.key = key <6>
===========unchanged ref 0=========== at: random randint = _inst.randint at: tests.lukas.XY_encrypt.encrypt self.ctext = self.ctext.replace(str(int(self.flip)), one).replace( str(int(not self.flip)), two ) self.ctext = self.to_binary().replace(" ", "") self.ctext = self.randomizer() if self.randomize == True else self.ctext
ciphey.basemods.Crackers.XandY/XandY.binary_to_ascii
Modified
Ciphey~Ciphey
997db87018fc5aaa5307e44dcd82f144a3a40992
Implement delimiter detection
<10>:<add> except UnicodeDecodeError as e: <del> except UnicodeDecodeError: <11>:<add> logger.trace("X-Y Cracker ecountered UnicodeDecodeError when trying to crack ctext.") <add> logger.trace(e)
# module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): @staticmethod def binary_to_ascii(variant): <0> # Convert the binary string to an integer with base 2 <1> binary_int = int(variant, 2) <2> byte_number = binary_int.bit_length() + 7 // 8 <3> <4> # Convert the resulting int to a bytearray and then decode it to ascii text <5> binary_array = binary_int.to_bytes(byte_number, "big") <6> try: <7> ascii_text = binary_array.decode() <8> logger.trace(f"Found possible solution: {ascii_text[:32]}...") <9> return ascii_text <10> except UnicodeDecodeError: <11> return "" <12>