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.basemods.Crackers.XandY/XandY.attemptCrack
Modified
Ciphey~Ciphey
997db87018fc5aaa5307e44dcd82f144a3a40992
Implement delimiter detection
<1>:<add> Checks an input if it only consists of two or three different letters. <del> Checks an input if it only consists of two different letters. <2>:<add> If this is the case, it attempts to regard those letters as <del> If this is the case, it attempts to regard those two letters as <3>:<add> 0 and 1 (with the third characters as an optional delimiter) and then <add> converts it to ascii text. <del> 0 and 1 and then converts it to ascii text. <9>:<del> ctext = ctext.lower().replace(" ", "").strip() <11>:<add> # Convert the ctext to all-lowercase and regex-match & replace all whitespace <add> ctext = ctext.lower() <add> ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) <add> <add> # cset contains every unique value in the ctext <del> # cset contains every unique value in the cstring <13>:<add> <add> if not 1 < len(cset) < 4: <del> if len(cset) != 2: <14>:<add> # We only consider inputs with two or three unique values <del> # We only consider inputs with exactly two unique values <15>:<add> logger.trace( <add> "String does not contain two or three unique values. Skipping X-Y..." <add> ) <del> logger.trace("String contains more than two unique values. Skipping X-Y...") <17>:<add> <18>:<add> logger.trace(f"String contains {len(cset)} unique values: {cset}") <del> logger.trace(f"String contains two unique values: {cset[0], cset[1]}") <19>:<add> <add> #
# module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> """ <1> Checks an input if it only consists of two different letters. <2> If this is the case, it attempts to regard those two letters as <3> 0 and 1 and then converts it to ascii text. <4> """ <5> logger.trace("Attempting X-Y replacement.") <6> variants = [] <7> candidates = [] <8> result = [] <9> ctext = ctext.lower().replace(" ", "").strip() <10> <11> # cset contains every unique value in the cstring <12> cset = list(set(list(ctext))) <13> if len(cset) != 2: <14> # We only consider inputs with exactly two unique values <15> logger.trace("String contains more than two unique values. Skipping X-Y...") <16> return None <17> else: <18> logger.trace(f"String contains two unique values: {cset[0], cset[1]}") <19> # Form both variants of the substitution <20> for i in range(2): <21> if i: <22> variants.append(ctext.replace(cset[0], "1").replace(cset[1], "0")) <23> else: <24> variants.append(ctext.replace(cset[0], "0").replace(cset[1], "1")) <25> # Apply function to both variants and strip stray NULL characters <26> for variant in variants: <27> candidates.append(self.binary_to_ascii(variant).strip("\x00")) <28> for i, candidate in enumerate(candidates): <29> if candidate != "": <30> keyinfo = f"{cset[0]} -> {i} & {cset[1]} -> {str(int(not i))}" <31> result.append(CrackResult(value=candidate, key_info=keyinfo)) <32> return result <33>
===========unchanged ref 0=========== 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: re UNICODE = RegexFlag.UNICODE sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): @staticmethod def binary_to_ascii(variant): # Convert the binary string to an integer with base 2 binary_int = int(variant, 2) byte_number = binary_int.bit_length() + 7 // 8 # Convert the resulting int to a bytearray and then decode it to ascii text binary_array = binary_int.to_bytes(byte_number, "big") try: ascii_text = binary_array.decode() logger.trace(f"Found possible solution: {ascii_text[:32]}...") return ascii_text + except UnicodeDecodeError as e: - except UnicodeDecodeError: + logger.trace("X-Y Cracker ecountered UnicodeDecodeError when trying to crack ctext.") + logger.trace(e) return ""
ciphey.basemods.Crackers.XandY/XandY.attemptCrack
Modified
Ciphey~Ciphey
0fd6639a80c17c2fd34715a9b061536753a3efdb
Fix ctext replacement bug
# module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> """ <1> Checks an input if it only consists of two or three different letters. <2> If this is the case, it attempts to regard those letters as <3> 0 and 1 (with the third characters as an optional delimiter) and then <4> converts it to ascii text. <5> """ <6> logger.trace("Attempting X-Y replacement.") <7> variants = [] <8> candidates = [] <9> result = [] <10> <11> # Convert the ctext to all-lowercase and regex-match & replace all whitespace <12> ctext = ctext.lower() <13> ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) <14> <15> # cset contains every unique value in the ctext <16> cset = list(set(list(ctext))) <17> <18> if not 1 < len(cset) < 4: <19> # We only consider inputs with two or three unique values <20> logger.trace( <21> "String does not contain two or three unique values. Skipping X-Y..." <22> ) <23> return None <24> <25> else: <26> logger.trace(f"String contains {len(cset)} unique values: {cset}") <27> <28> # In case of three unique values, we regard the least frequent character as the delimiter <29> if len(cset) == 3: <30> # Count each unique character in the set to determine the least frequent one <31> counting_list = [] <32> for char in cset: <33> counting_list.append(ctext.count(char)) <34> val, idx = min((val, idx) for (idx, val) in enumerate(counting_list)) <35> delimiter = cset[idx] <36> logger.trace( <37> f"{delimiter} occurs {val} times and is least frequent character & probable delimiter." <38> ) <39> # Remove the delimiter from the</s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 ctext.replace(delimiter, "") cset = list(set(list(ctext))) # Form both variants of the substitution for i in range(2): if i: variants.append(ctext.replace(cset[0], "1").replace(cset[1], "0")) else: variants.append(ctext.replace(cset[0], "0").replace(cset[1], "1")) # Apply function to both variants and strip stray NULL characters for variant in variants: candidates.append(self.binary_to_ascii(variant).strip("\x00")) for i, candidate in enumerate(candidates): if candidate != "": keyinfo = f"{cset[0]} -> {i} & {cset[1]} -> {str(int(not i))}" result.append(CrackResult(value=candidate, key_info=keyinfo)) logger.trace(f"X-Y cracker - Returning results: {result}") return result ===========unchanged ref 0=========== at: ciphey.basemods.Crackers.XandY.XandY binary_to_ascii(variant) 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: re UNICODE = RegexFlag.UNICODE sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr at: typing List = _alias(list, 1, inst=False, name='List')
tests.lukas/XY_encrypt.__init__
Modified
Ciphey~Ciphey
43a3190354a01d1d3ad46525669fb80bfed50a09
Move ASCII table to cipheydists
<0>:<add> self.ASCII = cipheydists.get_charset("asciiTable") <del> self.ASCII = list(chr(x) for x in range(32, 127))
# 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) for x in range(32, 127)) <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
6693007c71dddef6ccb3fe8c73e780bfb4a6834f
Implement requested changes
<11>:<add> logger.trace(f"X-Y Cracker ecountered UnicodeDecodeError when trying to crack ctext: {e}") <del> logger.trace("X-Y Cracker ecountered UnicodeDecodeError when trying to crack ctext.") <12>:<del> 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 as e: <11> logger.trace("X-Y Cracker ecountered UnicodeDecodeError when trying to crack ctext.") <12> logger.trace(e) <13> return "" <14>
ciphey.basemods.Crackers.XandY/XandY.attemptCrack
Modified
Ciphey~Ciphey
6693007c71dddef6ccb3fe8c73e780bfb4a6834f
Implement requested changes
<17>:<add> cset_len = len(cset) <18>:<add> if not 1 < cset_len < 4: <del> if not 1 < len(cset) < 4: <20>:<del> logger.trace( <21>:<add> logger.trace("String does not contain two or three unique values. Skipping X-Y...") <del> "String does not contain two or three unique values. Skipping X-Y..." <22>:<del> ) <26>:<add> logger.trace(f"String contains {cset_len} unique values: {cset}") <del> logger.trace(f"String contains {len(cset)} unique values: {cset}") <29>:<add> if cset_len == 3: <del> if len(cset) == 3: <34>:<add> val, index = min( <add> (val, index) for (index, val) in enumerate(counting_list) <del> val, idx = min((val, idx) for (idx, val) in enumerate(counting_list)) <35>:<add> ) <add> delimiter = cset[index] <del> delimiter = cset[idx]
# module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> """ <1> Checks an input if it only consists of two or three different letters. <2> If this is the case, it attempts to regard those letters as <3> 0 and 1 (with the third characters as an optional delimiter) and then <4> converts it to ascii text. <5> """ <6> logger.trace("Attempting X-Y replacement.") <7> variants = [] <8> candidates = [] <9> result = [] <10> <11> # Convert the ctext to all-lowercase and regex-match & replace all whitespace <12> ctext = ctext.lower() <13> ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) <14> <15> # cset contains every unique value in the ctext <16> cset = list(set(list(ctext))) <17> <18> if not 1 < len(cset) < 4: <19> # We only consider inputs with two or three unique values <20> logger.trace( <21> "String does not contain two or three unique values. Skipping X-Y..." <22> ) <23> return None <24> <25> else: <26> logger.trace(f"String contains {len(cset)} unique values: {cset}") <27> <28> # In case of three unique values, we regard the least frequent character as the delimiter <29> if len(cset) == 3: <30> # Count each unique character in the set to determine the least frequent one <31> counting_list = [] <32> for char in cset: <33> counting_list.append(ctext.count(char)) <34> val, idx = min((val, idx) for (idx, val) in enumerate(counting_list)) <35> delimiter = cset[idx] <36> logger.trace( <37> f"{delimiter} occurs {val} times and is least frequent character & probable delimiter." <38> ) <39> # Remove the delimiter from the</s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 ctext = ctext.replace(delimiter, "") cset = list(set(list(ctext))) # Form both variants of the substitution for i in range(2): if i: variants.append(ctext.replace(cset[0], "1").replace(cset[1], "0")) else: variants.append(ctext.replace(cset[0], "0").replace(cset[1], "1")) # Apply function to both variants and strip stray NULL characters for variant in variants: candidates.append(self.binary_to_ascii(variant).strip("\x00")) for i, candidate in enumerate(candidates): if candidate != "": keyinfo = f"{cset[0]} -> {i} & {cset[1]} -> {str(int(not i))}" result.append(CrackResult(value=candidate, key_info=keyinfo)) logger.trace(f"X-Y cracker - Returning results: {result}") return result ===========unchanged ref 0=========== at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: re UNICODE = RegexFlag.UNICODE sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr ===========changed ref 0=========== # module: ciphey.basemods.Crackers.XandY @registry.register class XandY(Cracker[str]): @staticmethod def binary_to_ascii(variant): # Convert the binary string to an integer with base 2 binary_int = int(variant, 2) byte_number = binary_int.bit_length() + 7 // 8 # Convert the resulting int to a bytearray and then decode it to ascii text binary_array = binary_int.to_bytes(byte_number, "big") try: ascii_text = binary_array.decode() logger.trace(f"Found possible solution: {ascii_text[:32]}...") return ascii_text except UnicodeDecodeError as e: + logger.trace(f"X-Y Cracker ecountered UnicodeDecodeError when trying to crack ctext: {e}") - logger.trace("X-Y Cracker ecountered UnicodeDecodeError when trying to crack ctext.") - logger.trace(e) return ""
ciphey.basemods.Decoders.atbash/Atbash.decode
Modified
Ciphey~Ciphey
300aa3835592245b353c5fa0b0b06f6886e08b90
Merge branch 'master' into master
<9>:<del> letters = list("abcdefghijklmnopqrstuvwxyz") <10>:<add> atbash_dict = {self.ALPHABET[i]: self.ALPHABET[::-1][i] for i in range(26)} <del> atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)}
# 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> for letter in ctext.lower(): <13> if letter in atbash_dict.keys(): <14> # Match every letter of the input to its atbash counterpoint <15> result += atbash_dict[letter] <16> else: <17> # If the current character is not in the defined alphabet, <18> # just accept it as-is (useful for numbers, punctuation,...) <19> result += letter <20> return fix_case(result, ctext) <21>
===========unchanged ref 0=========== at: ciphey.basemods.Decoders.atbash.Atbash.__init__ self.ALPHABET = config.get_resource(self._params()["dict"], WordList) at: ciphey.common fix_case(target: str, base: str) -> str 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.__init__
Modified
Ciphey~Ciphey
300aa3835592245b353c5fa0b0b06f6886e08b90
Merge branch 'master' into master
<1>:<add> self.ALPHABET = config.get_resource(self._params()["dict"], WordList)
# module: ciphey.basemods.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): def __init__(self, config: Config): <0> super().__init__(config) <1>
===========unchanged ref 0=========== at: ciphey.iface._config.Config get_resource(res_name: str, t: Optional[Type]=None) -> Any at: ciphey.iface._modules WordList = Set[str] at: ciphey.iface._modules.ConfigurableModule _params() at: ciphey.iface._modules.Decoder __init__(config: Config) ===========changed ref 0=========== # 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 = {self.ALPHABET[i]: self.ALPHABET[::-1][i] for i in range(26)} - atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)} for letter in ctext.lower(): 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)
ciphey.basemods.Decoders.atbash/Atbash.getParams
Modified
Ciphey~Ciphey
300aa3835592245b353c5fa0b0b06f6886e08b90
Merge branch 'master' into master
<0>:<add> return { <del> return None <1>:<add> "dict": ParamSpec( <add> desc="The alphabet used for the atbash operation.", <add> req=False, <add> default="cipheydists::list::englishAlphabet", <add> ) <add> }
# module: ciphey.basemods.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> return None <1>
===========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.Decoders.atbash @registry.register class Atbash(Decoder[str, str]): def __init__(self, config: Config): super().__init__(config) + self.ALPHABET = config.get_resource(self._params()["dict"], WordList) ===========changed ref 1=========== # 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 = {self.ALPHABET[i]: self.ALPHABET[::-1][i] for i in range(26)} - atbash_dict = {letters[i]: letters[::-1][i] for i in range(26)} for letter in ctext.lower(): 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)
ciphey.basemods.Decoders.base62/Base62.decode
Modified
Ciphey~Ciphey
e755fc926549494e9f7aa5898db274504f6c3d1e
Merge branch 'master' into bee-fix-310
<4>:<add> return base62.decodebytes(ctext).decode("utf-8") <del> return base62.encode(ctext).decode("utf-8")
# module: ciphey.basemods.Decoders.base62 @registry.register class Base62(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Performs Base62 decoding <2> """ <3> try: <4> return base62.encode(ctext).decode("utf-8") <5> except Exception: <6> return None <7>
===========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.morse/MorseCode.__init__
Modified
Ciphey~Ciphey
ad9323453514c5db24ca5be721d0e9943b6ab445
Merge branch 'master' into leet
<2>:<add> self._params()["dict"], ciphey.iface.Translation <del> self._params()["dict"], ciphey.iface.WordList
# module: ciphey.basemods.Decoders.morse @registry.register class MorseCode(ciphey.iface.Decoder[str, str]): def __init__(self, config: ciphey.iface.Config): <0> super().__init__(config) <1> self.MORSE_CODE_DICT = config.get_resource( <2> self._params()["dict"], ciphey.iface.WordList <3> ) <4> self.MORSE_CODE_DICT_INV = {v: k for k, v in self.MORSE_CODE_DICT.items()} <5>
===========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._modules.ConfigurableModule _params() at: ciphey.iface._modules.Decoder __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.iface._modules # Some common collection types Distribution = Dict[str, float] + Translation = Dict[str, str] WordList = Set[str]
ciphey.basemods.Decoders.galactic/Galactic.__init__
Modified
Ciphey~Ciphey
ad9323453514c5db24ca5be721d0e9943b6ab445
Merge branch 'master' into leet
<1>:<add> self.GALACTIC_DICT = config.get_resource(self._params()["dict"], Translation) <del> self.GALACTIC_DICT = config.get_resource(self._params()["dict"], WordList)
# module: ciphey.basemods.Decoders.galactic @registry.register class Galactic(Decoder[str, str]): def __init__(self, config: Config): <0> super().__init__(config) <1> self.GALACTIC_DICT = config.get_resource(self._params()["dict"], WordList) <2>
===========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._modules.ConfigurableModule _params() at: ciphey.iface._modules.Decoder __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== + # module: ciphey.basemods.Decoders.leet + + ===========changed ref 1=========== + # module: ciphey.basemods.Decoders.leet + @registry.register + class Leet(ciphey.iface.Decoder[str, str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 2=========== + # module: ciphey.basemods.Decoders.leet + @registry.register + class Leet(ciphey.iface.Decoder[str, str]): + @staticmethod + def getTarget() -> str: + return "leet" + ===========changed ref 3=========== + # module: ciphey.basemods.Decoders.leet + @registry.register + class Leet(ciphey.iface.Decoder[str, str]): + def decode(self, text: str) -> Optional[str]: + for src, dst in self.translate.items(): + text = text.replace(src, dst) + return text + ===========changed ref 4=========== # module: ciphey.iface._modules # Some common collection types Distribution = Dict[str, float] + Translation = Dict[str, str] WordList = Set[str] ===========changed ref 5=========== + # module: ciphey.basemods.Decoders.leet + @registry.register + class Leet(ciphey.iface.Decoder[str, str]): + def __init__(self, config: ciphey.iface.Config): + super().__init__(config) + self.translate = config.get_resource(self._params()["dict"], Translation) + ===========changed ref 6=========== + # module: ciphey.basemods.Decoders.leet + @registry.register + class Leet(ciphey.iface.Decoder[str, str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return { + "dict": ParamSpec( + desc="The leetspeak dictionary to use", + req=False, + default="cipheydists::translate::leet", + ) + } + ===========changed ref 7=========== # module: tests.test_main + def leet(): + res = decrypt( + Config().library_default().complete_config(), + "|-|3770 my nam3 is 833 and 1 lIke D06 AND 4|>|>13 4 7R33", + ) + assert res.lower() == answer_str + ===========changed ref 8=========== # module: ciphey.basemods.Decoders.morse @registry.register class MorseCode(ciphey.iface.Decoder[str, str]): def __init__(self, config: ciphey.iface.Config): super().__init__(config) self.MORSE_CODE_DICT = config.get_resource( + self._params()["dict"], ciphey.iface.Translation - self._params()["dict"], ciphey.iface.WordList ) self.MORSE_CODE_DICT_INV = {v: k for k, v in self.MORSE_CODE_DICT.items()}
tests.test_main/test_base62
Modified
Ciphey~Ciphey
f9c91c25527155d491a62681c3cad5786a78d65f
Fix Base62 and Base91 tests
<1>:<add> Config().library_default().complete_config(), <del> Config().library_default().complete_config(), ".3vQº·îP=.ã.ÿî̤U¤.[hù>.Ñü.¨zj{D" <2>:<add> "2mQvnz9Yevvb7DRCuyDltsP31vJLToR5pjE9orWkzHMUsht2kbC96PLbZ1sdIocsGHENrzC2n", <3>:<del> res = res.decode("utf-8")
# module: tests.test_main - @pytest.mark.skip(reason="This test appears to run infiniitely.") def test_base62(): <0> res = decrypt( <1> Config().library_default().complete_config(), ".3vQº·îP=.ã.ÿî̤U¤.[hù>.Ñü.¨zj{D" <2> ) <3> res = res.decode("utf-8") <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" at: tests.test_main.test_base58_normal res = decrypt( Config().library_default().complete_config(), "6qYhNwsP46Mn4gy6gyANfsMm2icAxGFA6gnFjVm9phYHeby7PZm3vthiXxSU77teQgTFGbHETn", )
ciphey.basemods.Searchers.ausearch/AuSearch.recursive_expand
Modified
Ciphey~Ciphey
9f67b7b343232c23d009cd6f4ae45dfef812894f
Disabled nested encryption
<0>:<add> self.expand_decodings(node) <del> logger.trace(f"Expanding depth {node.depth} encodings") <2>:<add> # Doing this last allows us to catch simple nested encodings faster <add> if not nested or self.enable_nested: <add> self.expand_crackers(node) <del> val = node.level.result.value <4>:<del> for decoder in self.get_decoders_for(type(val)): <5>:<del> inst = self._config()(decoder) <6>:<del> res = inst(val) <7>:<del> if res is None: <8>:<del> continue <9>:<del> try: <10>:<del> new_node = Node.decoding( <11>:<del> config=self._config(), route=inst, result=res, source=node <12>:<del> ) <13>:<del> except DuplicateNode: <14>:<del> continue <15>:<del> <16>:<del> logger.trace(f"Nesting encodings") <17>:<del> self.recursive_expand(new_node) <18>:<del> # Now we add the cracker edges <19>:<del> # Doing this last allows us to catch nested encodings faster <20>:<del> self.expand_crackers(node) <21>:<del>
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def recursive_expand(self, node: Node, nested: bool=True) -> None: - def recursive_expand(self, node: Node) -> None: <0> logger.trace(f"Expanding depth {node.depth} encodings") <1> <2> val = node.level.result.value <3> <4> for decoder in self.get_decoders_for(type(val)): <5> inst = self._config()(decoder) <6> res = inst(val) <7> if res is None: <8> continue <9> try: <10> new_node = Node.decoding( <11> config=self._config(), route=inst, result=res, source=node <12> ) <13> except DuplicateNode: <14> continue <15> <16> logger.trace(f"Nesting encodings") <17> self.recursive_expand(new_node) <18> # Now we add the cracker edges <19> # Doing this last allows us to catch nested encodings faster <20> self.expand_crackers(node) <21>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def expand_decodings(self, node: None) -> None: + logger.trace(f"Expanding depth {node.depth} encodings") + + val = node.level.result.value + + for decoder in self.get_decoders_for(type(val)): + inst = self._config()(decoder) + res = inst(val) + if res is None: + continue + try: + new_node = Node.decoding( + config=self._config(), route=inst, result=res, source=node + ) + except DuplicateNode: + continue + + logger.trace(f"Nesting encodings") + self.recursive_expand(new_node, False) +
ciphey.basemods.Searchers.ausearch/AuSearch.search
Modified
Ciphey~Ciphey
9f67b7b343232c23d009cd6f4ae45dfef812894f
Disabled nested encryption
<15>:<add> self.recursive_expand(root, False) <del> self.recursive_expand(root)
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: <0> logger.trace( <1> f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""" <2> ) <3> <4> try: <5> root = Node.root(self._config(), ctext) <6> except DuplicateNode: <7> return None <8> <9> if type(ctext) == self._config().objs["format"]["out"]: <10> check_res = self._config().objs["checker"](ctext) <11> if check_res is not None: <12> return SearchResult(check_res=check_res, path=[root.level]) <13> <14> try: <15> self.recursive_expand(root) <16> <17> while True: <18> if self.work.empty(): <19> break <20> # Get the highest level result <21> chunk = self.work.get_work_chunk() <22> infos = [i.info for i in chunk] <23> # Work through all of this level's results <24> while len(chunk) != 0: <25> # if self.disable_priority: <26> # chunk += self.work.get_work_chunk() <27> # infos = [i.info for i in chunk] <28> <29> logger.trace(f"{len(infos)} remaining on this level") <30> step_res = cipheycore.ausearch_minimise(infos) <31> edge: Edge = chunk.pop(step_res.index) <32> logger.trace( <33> f"Weight is currently {step_res.weight} " <34> f"when we pick {type(edge.route).__name__.lower()}" <35> ) <36> del infos[step_res.index] <37> <38> # Expand the node <39> res = edge.route(edge.source.level.result.value) <40> if res is None: <41> continue <42> for i in res: <43> try:</s>
===========below chunk 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 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") ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def expand_decodings(self, node: None) -> None: + logger.trace(f"Expanding depth {node.depth} encodings") + + val = node.level.result.value + + for decoder in self.get_decoders_for(type(val)): + inst = self._config()(decoder) + res = inst(val) + if res is None: + continue + try: + new_node = Node.decoding( + config=self._config(), route=inst, result=res, source=node + ) + except DuplicateNode: + continue + + logger.trace(f"Nesting encodings") + self.recursive_expand(new_node, False) + ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def recursive_expand(self, node: Node, nested: bool=True) -> None: - def recursive_expand(self, node: Node) -> None: + self.expand_decodings(node) - logger.trace(f"Expanding depth {node.depth} encodings") + # Doing this last allows us to catch simple nested encodings faster + if not nested or self.enable_nested: + self.expand_crackers(node) - val = node.level.result.value - for decoder in self.get_decoders_for(type(val)): - inst = self._config()(decoder) - res = inst(val) - if res is None: - continue - try: - new_node = Node.decoding( - config=self._config(), route=inst, result=res, source=node - ) - except DuplicateNode: - continue - - logger.trace(f"Nesting encodings") - self.recursive_expand(new_node) - # Now we add the cracker edges - # Doing this last allows us to catch nested encodings faster - self.expand_crackers(node) -
ciphey.basemods.Searchers.ausearch/AuSearch.__init__
Modified
Ciphey~Ciphey
9f67b7b343232c23d009cd6f4ae45dfef812894f
Disabled nested encryption
<6>:<add> self.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"]))
# 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.priority_cap = int(self._params()["priority_cap"]) <6>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def expand_decodings(self, node: None) -> None: + logger.trace(f"Expanding depth {node.depth} encodings") + + val = node.level.result.value + + for decoder in self.get_decoders_for(type(val)): + inst = self._config()(decoder) + res = inst(val) + if res is None: + continue + try: + new_node = Node.decoding( + config=self._config(), route=inst, result=res, source=node + ) + except DuplicateNode: + continue + + logger.trace(f"Nesting encodings") + self.recursive_expand(new_node, False) + ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def recursive_expand(self, node: Node, nested: bool=True) -> None: - def recursive_expand(self, node: Node) -> None: + self.expand_decodings(node) - logger.trace(f"Expanding depth {node.depth} encodings") + # Doing this last allows us to catch simple nested encodings faster + if not nested or self.enable_nested: + self.expand_crackers(node) - val = node.level.result.value - for decoder in self.get_decoders_for(type(val)): - inst = self._config()(decoder) - res = inst(val) - if res is None: - continue - try: - new_node = Node.decoding( - config=self._config(), route=inst, result=res, source=node - ) - except DuplicateNode: - continue - - logger.trace(f"Nesting encodings") - self.recursive_expand(new_node) - # Now we add the cracker edges - # Doing this last allows us to catch nested encodings faster - self.expand_crackers(node) - ===========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, False) - 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: # chunk += self.work.get_work_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( config=self._config(), edge_template=edge, result=i )</s> ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s> 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
9f67b7b343232c23d009cd6f4ae45dfef812894f
Disabled nested encryption
<1>:<add> "enable_nested": ParamSpec(req=False, <add> desc="Enables nested ciphers. " <add> "Incredibly slow, and not guaranteed to terminate", <add> default="False"), <add>
# 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="True"), <5> "priority_cap": ParamSpec(req=False, <6> desc="Sets the maximum depth before we give up on the priority queue", <7> default="3") <8> } <9>
===========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.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"])) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def expand_decodings(self, node: None) -> None: + logger.trace(f"Expanding depth {node.depth} encodings") + + val = node.level.result.value + + for decoder in self.get_decoders_for(type(val)): + inst = self._config()(decoder) + res = inst(val) + if res is None: + continue + try: + new_node = Node.decoding( + config=self._config(), route=inst, result=res, source=node + ) + except DuplicateNode: + continue + + logger.trace(f"Nesting encodings") + self.recursive_expand(new_node, False) + ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def recursive_expand(self, node: Node, nested: bool=True) -> None: - def recursive_expand(self, node: Node) -> None: + self.expand_decodings(node) - logger.trace(f"Expanding depth {node.depth} encodings") + # Doing this last allows us to catch simple nested encodings faster + if not nested or self.enable_nested: + self.expand_crackers(node) - val = node.level.result.value - for decoder in self.get_decoders_for(type(val)): - inst = self._config()(decoder) - res = inst(val) - if res is None: - continue - try: - new_node = Node.decoding( - config=self._config(), route=inst, result=res, source=node - ) - except DuplicateNode: - continue - - logger.trace(f"Nesting encodings") - self.recursive_expand(new_node) - # Now we add the cracker edges - # Doing this last allows us to catch nested encodings faster - self.expand_crackers(node) - ===========changed ref 3=========== # 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, False) - 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: # chunk += self.work.get_work_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( config=self._config(), edge_template=edge, result=i )</s> ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s> 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.caesar/Caesar.attemptCrack
Modified
Ciphey~Ciphey
9f67b7b343232c23d009cd6f4ae45dfef812894f
Disabled nested encryption
<0>:<add> logger.debug(f"Trying caesar cipher on {ctext}") <del> logger.debug("Trying caesar cipher")
# 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=fix_case(translated, ctext), 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.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.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"])) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "enable_nested": ParamSpec(req=False, + desc="Enables nested ciphers. " + "Incredibly slow, and not guaranteed to terminate", + default="False"), + "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", default="True"), "priority_cap": ParamSpec(req=False, desc="Sets the maximum depth before we give up on the priority queue", default="3") } ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def expand_decodings(self, node: None) -> None: + logger.trace(f"Expanding depth {node.depth} encodings") + + val = node.level.result.value + + for decoder in self.get_decoders_for(type(val)): + inst = self._config()(decoder) + res = inst(val) + if res is None: + continue + try: + new_node = Node.decoding( + config=self._config(), route=inst, result=res, source=node + ) + except DuplicateNode: + continue + + logger.trace(f"Nesting encodings") + self.recursive_expand(new_node, False) + ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): + def recursive_expand(self, node: Node, nested: bool=True) -> None: - def recursive_expand(self, node: Node) -> None: + self.expand_decodings(node) - logger.trace(f"Expanding depth {node.depth} encodings") + # Doing this last allows us to catch simple nested encodings faster + if not nested or self.enable_nested: + self.expand_crackers(node) - val = node.level.result.value - for decoder in self.get_decoders_for(type(val)): - inst = self._config()(decoder) - res = inst(val) - if res is None: - continue - try: - new_node = Node.decoding( - config=self._config(), route=inst, result=res, source=node - ) - except DuplicateNode: - continue - - logger.trace(f"Nesting encodings") - self.recursive_expand(new_node) - # Now we add the cracker edges - # Doing this last allows us to catch nested encodings faster - self.expand_crackers(node) - ===========changed ref 4=========== # 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, False) - 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: # chunk += self.work.get_work_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( config=self._config(), edge_template=edge, result=i )</s> ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s> 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.xorcrypt/XorCrypt.attemptCrack
Modified
Ciphey~Ciphey
44709046f4b25b4932dac3d1a23c824d55b47ae1
Integrated latest cipheycore, broke vigenere
<0>:<add> logger.debug(f"Trying xorcrypt cipher on {base64.b64encode(ctext)}") <del> logger.debug("Trying xorcrypt cipher") <18>:<add> <19>:<add> <add> if len < 2: <add> return [] <add> <add> ret = [] <add> # Fuzz around <add> for i in range(min(len - 2, 2), len + 2): <add> ret += self.crackOne( <del> return self.crackOne( <20>:<del> ctext, <21>:<del> self.cache.get_or_update( <23>:<add> self.cache.get_or_update( <add> ctext, <add> f"xorcrypt::{len}", <del> f"xorcrypt::{len}", <24>:<add> lambda: cipheycore.analyse_bytes(ctext, len), <del> lambda: cipheycore.analyse_bytes(ctext, len), <25>:<add> ) <add> ) <del> ), <26>:<del> )
# module: ciphey.basemods.Crackers.xorcrypt @registry.register class XorCrypt(ciphey.iface.Cracker[bytes]): def attemptCrack(self, ctext: bytes) -> List[CrackResult]: <0> logger.debug("Trying xorcrypt cipher") <1> <2> # Analysis must be done here, where we know the case for the cache <3> if self.keysize is not None: <4> return self.crackOne( <5> ctext, <6> self.cache.get_or_update( <7> ctext, <8> f"xorcrypt::{self.keysize}", <9> lambda: cipheycore.analyse_bytes(ctext, self.keysize), <10> ), <11> ) <12> else: <13> len = self.cache.get_or_update( <14> ctext, <15> f"xorcrypt::likely_lens", <16> lambda: cipheycore.xorcrypt_guess_len(ctext), <17> ) <18> logger.trace(f"Got possible length {len}") <19> return self.crackOne( <20> ctext, <21> self.cache.get_or_update( <22> ctext, <23> f"xorcrypt::{len}", <24> lambda: cipheycore.analyse_bytes(ctext, len), <25> ), <26> ) <27>
===========unchanged ref 0=========== at: base64 b64encode(s: _encodable, altchars: Optional[bytes]=...) -> bytes at: ciphey.basemods.Crackers.xorcrypt.XorCrypt crackOne(ctext: bytes, analysis: cipheycore.windowed_analysis_res) -> List[CrackResult] at: ciphey.basemods.Crackers.xorcrypt.XorCrypt.__init__ 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')
ciphey.basemods.Crackers.xorcrypt/XorCrypt.getParams
Modified
Ciphey~Ciphey
44709046f4b25b4932dac3d1a23c824d55b47ae1
Integrated latest cipheycore, broke vigenere
<13>:<add> default=0.001, <del> default=0.01,
# module: ciphey.basemods.Crackers.xorcrypt @registry.register class XorCrypt(ciphey.iface.Cracker[bytes]): @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> "keysize": ciphey.iface.ParamSpec( <7> desc="A key size that should be used. If not given, will attempt to work it out", <8> req=False, <9> ), <10> "p_value": ciphey.iface.ParamSpec( <11> desc="The p-value to use for windowed frequency analysis", <12> req=False, <13> default=0.01, <14> ), <15> } <16>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.xorcrypt.XorCrypt crackOne(ctext: bytes, analysis: cipheycore.windowed_analysis_res) -> List[CrackResult] at: ciphey.basemods.Crackers.xorcrypt.XorCrypt.__init__ self.cache = config.cache at: ciphey.basemods.Crackers.xorcrypt.XorCrypt.attemptCrack len = self.cache.get_or_update( ctext, f"xorcrypt::likely_lens", lambda: cipheycore.xorcrypt_guess_len(ctext), ) at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) 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.Crackers.xorcrypt @registry.register class XorCrypt(ciphey.iface.Cracker[bytes]): def attemptCrack(self, ctext: bytes) -> List[CrackResult]: + logger.debug(f"Trying xorcrypt cipher on {base64.b64encode(ctext)}") - logger.debug("Trying xorcrypt cipher") # Analysis must be done here, where we know the case for the cache if self.keysize is not None: return self.crackOne( ctext, self.cache.get_or_update( ctext, f"xorcrypt::{self.keysize}", lambda: cipheycore.analyse_bytes(ctext, self.keysize), ), ) else: len = self.cache.get_or_update( ctext, f"xorcrypt::likely_lens", lambda: cipheycore.xorcrypt_guess_len(ctext), ) + logger.trace(f"Got possible length {len}") + + if len < 2: + return [] + + ret = [] + # Fuzz around + for i in range(min(len - 2, 2), len + 2): + ret += self.crackOne( - return self.crackOne( - ctext, - self.cache.get_or_update( ctext, + self.cache.get_or_update( + ctext, + f"xorcrypt::{len}", - f"xorcrypt::{len}", + lambda: cipheycore.analyse_bytes(ctext, len), - lambda: cipheycore.analyse_bytes(ctext, len), + ) + ) - ), - )
ciphey.basemods.Searchers.ausearch/PriorityWorkQueue.add_work
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<0>:<add> logger.trace( <add> f"""Adding work at depth {priority}""" <add> ) <add>
# module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: <0> idx = bisect.bisect_left(self._sorted_priorities, priority) <1> if ( <2> idx == len(self._sorted_priorities) <3> or self._sorted_priorities[idx] != priority <4> ): <5> self._sorted_priorities.insert(idx, priority) <6> self._queues.setdefault(priority, []).extend(work) <7>
ciphey.basemods.Searchers.ausearch/AuSearch.expand_crackers
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<0>:<add> if node.depth >= self.max_cipher_depth: <add> return <add> <1>:<del>
# 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> priority = min(node.depth, self.priority_cap) <8> if self.invert_priority: <9> priority = -priority <10> <11> self.work.add_work(priority, additional_work) <12>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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.Searchers.ausearch/AuSearch.expand_decodings
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<0>:<del> logger.trace(f"Expanding depth {node.depth} encodings") <1>:<del>
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: <0> logger.trace(f"Expanding depth {node.depth} encodings") <1> <2> val = node.level.result.value <3> <4> for decoder in self.get_decoders_for(type(val)): <5> inst = self._config()(decoder) <6> res = inst(val) <7> if res is None: <8> continue <9> try: <10> new_node = Node.decoding( <11> config=self._config(), route=inst, result=res, source=node <12> ) <13> except DuplicateNode: <14> continue <15> <16> logger.trace(f"Nesting encodings") <17> self.recursive_expand(new_node, False) <18>
===========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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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.Searchers.ausearch/AuSearch.recursive_expand
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<0>:<add> if node.depth >= self.max_depth: <add> return <add> <add> logger.trace(f"Expanding depth {node.depth}") <add>
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: <0> self.expand_decodings(node) <1> <2> # Doing this last allows us to catch simple nested encodings faster <3> if not nested or self.enable_nested: <4> self.expand_crackers(node) <5>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: - logger.trace(f"Expanding depth {node.depth} encodings") - val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False) ===========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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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.Searchers.ausearch/AuSearch.search
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<25>:<add> max_depth = 0 <add> for i in chunk: <add> if i.source.depth > max_depth: <add> max_depth = i.source.depth <add> logger.debug(f"At depth {chunk[0].source.depth}") <add> <34>:<add> f"when we pick {type(edge.route).__name__.lower()} " <del> f"when we pick {type(edge.route).__name__.lower()}" <35>:<add> f"with depth {edge.source.depth}"
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: <0> logger.trace( <1> f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""" <2> ) <3> <4> try: <5> root = Node.root(self._config(), ctext) <6> except DuplicateNode: <7> return None <8> <9> if type(ctext) == self._config().objs["format"]["out"]: <10> check_res = self._config().objs["checker"](ctext) <11> if check_res is not None: <12> return SearchResult(check_res=check_res, path=[root.level]) <13> <14> try: <15> self.recursive_expand(root, False) <16> <17> while True: <18> if self.work.empty(): <19> break <20> # Get the highest level result <21> chunk = self.work.get_work_chunk() <22> infos = [i.info for i in chunk] <23> # Work through all of this level's results <24> while len(chunk) != 0: <25> # if self.disable_priority: <26> # chunk += self.work.get_work_chunk() <27> # infos = [i.info for i in chunk] <28> <29> logger.trace(f"{len(infos)} remaining on this level") <30> step_res = cipheycore.ausearch_minimise(infos) <31> edge: Edge = chunk.pop(step_res.index) <32> logger.trace( <33> f"Weight is currently {step_res.weight} " <34> f"when we pick {type(edge.route).__name__.lower()}" <35> ) <36> del infos[step_res.index] <37> <38> # Expand the node <39> res = edge.route(edge.source.level.result.value) <40> if res is None: <41> continue <42> for i in res: <43> </s>
===========below chunk 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 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") ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: - logger.trace(f"Expanding depth {node.depth} encodings") - val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False) ===========changed ref 2=========== # 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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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.Searchers.ausearch/AuSearch.__init__
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<7>:<add> self.max_cipher_depth = int(self._params()["max_cipher_depth"]) <add> if self.max_cipher_depth == 0: <add> self.max_cipher_depth = math.inf <add> self.max_depth = int(self._params()["max_depth"]) <add> if self.max_depth == 0: <add> self.max_depth = math.inf
# 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.priority_cap = int(self._params()["priority_cap"]) <6> self.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"])) <7>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: - logger.trace(f"Expanding depth {node.depth} encodings") - val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False) ===========changed ref 2=========== # 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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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 4=========== # 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, False) 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: + max_depth = 0 + for i in chunk: + if i.source.depth > max_depth: + max_depth = i.source.depth + logger.debug(f"At depth {chunk[0].source.depth}") + # if self.disable_priority: # chunk += self.work.get_work_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()} " - f"when we pick {type(edge.route).__name__.lower()}" + f"with depth {edge.source.depth}" </s> ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s>when we pick {type(edge.route).__name__.lower()}" + f"with depth {edge.source.depth}" ) 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( 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
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<9>:<add> default="False"), <add> "max_cipher_depth": ParamSpec(req=False, <add> desc="The depth at which we stop trying to crack ciphers. " <add> "Set to 0 to disable", <add> default="5"), <del> default="True"), <10>:<add> "max_depth": ParamSpec(req=False, <add> desc="The depth at which we give up. " <add> "Set to 0 to disable", <add> default="0"), <11>:<add> desc="Sets the maximum depth before we give up ordering items.", <del> desc="Sets the maximum depth before we give up on the priority queue", <12>:<add> default="2"), <del> default="3")
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> return { <1> "enable_nested": ParamSpec(req=False, <2> desc="Enables nested ciphers. " <3> "Incredibly slow, and not guaranteed to terminate", <4> default="False"), <5> <6> "invert_priority": ParamSpec(req=False, <7> desc="Causes more complex encodings to be looked at first. " <8> "Good for deeply buried encodings.", <9> default="True"), <10> "priority_cap": ParamSpec(req=False, <11> desc="Sets the maximum depth before we give up on the priority queue", <12> default="3") <13> } <14>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: - logger.trace(f"Expanding depth {node.depth} encodings") - val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False) ===========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.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"])) + self.max_cipher_depth = int(self._params()["max_cipher_depth"]) + if self.max_cipher_depth == 0: + self.max_cipher_depth = math.inf + self.max_depth = int(self._params()["max_depth"]) + if self.max_depth == 0: + self.max_depth = math.inf ===========changed ref 3=========== # 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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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 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, False) 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: + max_depth = 0 + for i in chunk: + if i.source.depth > max_depth: + max_depth = i.source.depth + logger.debug(f"At depth {chunk[0].source.depth}") + # if self.disable_priority: # chunk += self.work.get_work_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()} " - f"when we pick {type(edge.route).__name__.lower()}" + f"with depth {edge.source.depth}" </s> ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s>when we pick {type(edge.route).__name__.lower()}" + f"with depth {edge.source.depth}" ) 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( 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.xorcrypt/XorCrypt.getInfo
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<24>:<add> success_runtime=2e-3, <del> success_runtime=2e-4, <25>:<add> failure_runtime=2e-2, <del> failure_runtime=2e-4, <31>:<add> success_runtime=2e-3, <del> success_runtime=2e-4, <32>:<add> failure_runtime=2e-2, <del> failure_runtime=2e-4,
# module: ciphey.basemods.Crackers.xorcrypt @registry.register class XorCrypt(ciphey.iface.Cracker[bytes]): def getInfo(self, ctext: bytes) -> CrackInfo: <0> if self.keysize is not None: <1> analysis = self.cache.get_or_update( <2> ctext, <3> f"xorcrypt::{self.keysize}", <4> lambda: cipheycore.analyse_string(ctext, self.keysize, self.group), <5> ) <6> <7> return CrackInfo( <8> success_likelihood=cipheycore.xorcrypt_detect(analysis, self.expected), <9> # TODO: actually calculate runtimes <10> success_runtime=1e-4, <11> failure_runtime=1e-4, <12> ) <13> <14> keysize = self.cache.get_or_update( <15> ctext, <16> f"xorcrypt::likely_lens", <17> lambda: cipheycore.xorcrypt_guess_len(ctext), <18> ) <19> <20> if keysize == 1: <21> return CrackInfo( <22> success_likelihood=0, <23> # TODO: actually calculate runtimes <24> success_runtime=2e-4, <25> failure_runtime=2e-4, <26> ) <27> <28> return CrackInfo( <29> success_likelihood=0.9, # Dunno, but it's quite likely <30> # TODO: actually calculate runtimes <31> success_runtime=2e-4, <32> failure_runtime=2e-4, <33> ) <34>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.xorcrypt.XorCrypt.__init__ 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 CrackInfo(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker getInfo(self, ctext: T) -> CrackInfo ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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 2=========== # 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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: - logger.trace(f"Expanding depth {node.depth} encodings") - val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False) ===========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.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"])) + self.max_cipher_depth = int(self._params()["max_cipher_depth"]) + if self.max_cipher_depth == 0: + self.max_cipher_depth = math.inf + self.max_depth = int(self._params()["max_depth"]) + if self.max_depth == 0: + self.max_depth = math.inf ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "enable_nested": ParamSpec(req=False, desc="Enables nested ciphers. " "Incredibly slow, and not guaranteed to terminate", default="False"), "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", + default="False"), + "max_cipher_depth": ParamSpec(req=False, + desc="The depth at which we stop trying to crack ciphers. " + "Set to 0 to disable", + default="5"), - default="True"), + "max_depth": ParamSpec(req=False, + desc="The depth at which we give up. " + "Set to 0 to disable", + default="0"), "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up ordering items.", - desc="Sets the maximum depth before we give up on the priority queue", + default="2"), - default="3") }
ciphey.basemods.Crackers.vigenere/Vigenere.getInfo
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<7>:<add> val = cipheycore.vigenere_detect(analysis, self.expected) <add> <add> logger.debug(f"Vigenere has likelihood {val}") <add> <8>:<add> success_likelihood=val, <del> success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), <10>:<add> success_runtime=1e-3, <del> success_runtime=1e-4, <11>:<add> failure_runtime=1e-2, <del> failure_runtime=1e-4, <17>:<add> lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.detect_p_value), <del> lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), <19>:<add> <add> likely_lens_cpy = likely_lens <add> # Filter out the lens that make no sense <add> likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] <29>:<add> success_runtime=2e-3, <del> success_runtime=2e-4, <30>:<add> failure_runtime=2e-2, <del> failure_runtime=2e-4, <33>:<add> logger.debug(f"Vigenere has likelihood {likely
# 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.lower(), 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.lower(), 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, f"vigenere::{keysize.len}", lambda: keysize.tab <24> ) <25> if len(likely_lens) == 0: <26> return CrackInfo( <27> success_likelihood=0, <28> # TODO: actually calculate runtimes <29> success_runtime=2e-4, <30> failure_runtime=2e-4, <31> ) <32> <33> return CrackInfo( <34> success_likelihood=0 * likely_lens[0].p_value, <35> # TODO: actually calculate runtimes <36> success_runtime=2e-4, <37> failure_runtime=2e-4, <38> ) <39>
===========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.detect_p_value = float(self._params()["detect_p_value"]) self.MAX_KEY_LENGTH = 16 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) at: ciphey.iface._modules.Cracker getInfo(self, ctext: T) -> CrackInfo ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 1=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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 2=========== # 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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: - logger.trace(f"Expanding depth {node.depth} encodings") - val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False) ===========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.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"])) + self.max_cipher_depth = int(self._params()["max_cipher_depth"]) + if self.max_cipher_depth == 0: + self.max_cipher_depth = math.inf + self.max_depth = int(self._params()["max_depth"]) + if self.max_depth == 0: + self.max_depth = math.inf ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "enable_nested": ParamSpec(req=False, desc="Enables nested ciphers. " "Incredibly slow, and not guaranteed to terminate", default="False"), "invert_priority": ParamSpec(req=False, desc="Causes more complex encodings to be looked at first. " "Good for deeply buried encodings.", + default="False"), + "max_cipher_depth": ParamSpec(req=False, + desc="The depth at which we stop trying to crack ciphers. " + "Set to 0 to disable", + default="5"), - default="True"), + "max_depth": ParamSpec(req=False, + desc="The depth at which we give up. " + "Set to 0 to disable", + default="0"), "priority_cap": ParamSpec(req=False, + desc="Sets the maximum depth before we give up ordering items.", - desc="Sets the maximum depth before we give up on the priority queue", + default="2"), - default="3") }
ciphey.basemods.Crackers.vigenere/Vigenere.crackOne
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<3>:<add> if len(possible_keys) > self.clamp: <add> possible_keys = possible_keys[:self.clamp] <12>:<add> misc_info=f"p-value was {candidate.p_value}"
# 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 ) -> List[CrackResult]: <0> possible_keys = cipheycore.vigenere_crack( <1> analysis, self.expected, self.group, self.p_value <2> ) <3> logger.trace( <4> f"Vigenere crack got keys: {[[i for i in candidate.key] for candidate in possible_keys]}" <5> ) <6> # if len(possible_keys) and possible_keys[0].p_value < 0.9999999: <7> # raise 0 <8> return [ <9> CrackResult( <10> value=fix_case(cipheycore.vigenere_decrypt(ctext, candidate.key, self.group), real_ctext), <11> key_info="".join([self.group[i] for i in candidate.key]), <12> ) <13> for candidate in possible_keys[: min(len(possible_keys), 10)] <14> ] <15>
===========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"]) self.clamp = int(self._params()["clamp"]) at: ciphey.basemods.Crackers.vigenere.Vigenere.getInfo 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.detect_p_value), ) likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) 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: 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), ) + val = cipheycore.vigenere_detect(analysis, self.expected) + + logger.debug(f"Vigenere has likelihood {val}") + return CrackInfo( + success_likelihood=val, - success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes + success_runtime=1e-3, - success_runtime=1e-4, + failure_runtime=1e-2, - 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.detect_p_value), - lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), ) + + likely_lens_cpy = likely_lens + # Filter out the lens that make no sense + likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] for keysize in likely_lens: # Store the analysis analysis = self.cache.get_or_update( ctext, f"vigenere::{keysize.len}",</s> ===========changed ref 1=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: # offset: 1 <s> = 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-3, - success_runtime=2e-4, + failure_runtime=2e-2, - failure_runtime=2e-4, ) + logger.debug(f"Vigenere has likelihood {likely_lens[0].p_value} with lens {[i.len for i in likely_lens]}") + return CrackInfo( + success_likelihood=likely_lens[0].p_value, - success_likelihood=0 * likely_lens[0].p_value, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 3=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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 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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work) ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: None) -> None: - logger.trace(f"Expanding depth {node.depth} encodings") - val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False)
ciphey.basemods.Crackers.vigenere/Vigenere.getParams
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<23>:<add> default=0.5, <add> ), <add> "detect_p_value": ciphey.iface.ParamSpec( <add> desc="The p-value to use for the detection of Vigenere length", <add> req=False, <24>:<add> ), <add> "clamp": ciphey.iface.ParamSpec( <add> desc="The maximum number of candidates that can be returned per key len", <add> req=False, <add> default=10,
# 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.01, <24> ), <25> } <26>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere.__init__ self.group = list(self._params()["group"]) self.cache = config.cache at: ciphey.basemods.Crackers.vigenere.Vigenere.attemptCrack message = ctext message = ctext.lower() arrs = [] at: ciphey.iface._config.Cache get_or_update(ctext: Any, keyname: str, get_value: Callable[[], Any]) 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.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def crackOne( self, ctext: str, analysis: cipheycore.windowed_analysis_res, real_ctext: str ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) + if len(possible_keys) > self.clamp: + possible_keys = possible_keys[:self.clamp] 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), key_info="".join([self.group[i] for i in candidate.key]), + misc_info=f"p-value was {candidate.p_value}" ) 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), ) + val = cipheycore.vigenere_detect(analysis, self.expected) + + logger.debug(f"Vigenere has likelihood {val}") + return CrackInfo( + success_likelihood=val, - success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes + success_runtime=1e-3, - success_runtime=1e-4, + failure_runtime=1e-2, - 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.detect_p_value), - lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), ) + + likely_lens_cpy = likely_lens + # Filter out the lens that make no sense + likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] for keysize in likely_lens: # Store the analysis analysis = self.cache.get_or_update( ctext, f"vigenere::{keysize.len}",</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> = 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-3, - success_runtime=2e-4, + failure_runtime=2e-2, - failure_runtime=2e-4, ) + logger.debug(f"Vigenere has likelihood {likely_lens[0].p_value} with lens {[i.len for i in likely_lens]}") + return CrackInfo( + success_likelihood=likely_lens[0].p_value, - 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.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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 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: + if node.depth >= self.max_cipher_depth: + return + 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.invert_priority: priority = -priority self.work.add_work(priority, additional_work)
ciphey.basemods.Crackers.vigenere/Vigenere.__init__
Modified
Ciphey~Ciphey
0972fd66c079e5221fb8bfb0a18b3beb8a9a03b1
Should work now
<11>:<add> self.detect_p_value = float(self._params()["detect_p_value"]) <add> self.clamp = int(self._params()["clamp"])
# 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 = float(self._params()["p_value"]) <11> self.MAX_KEY_LENGTH = 16 <12>
===========unchanged ref 0=========== at: ciphey.iface._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) ===========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 ) -> List[CrackResult]: possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) + if len(possible_keys) > self.clamp: + possible_keys = possible_keys[:self.clamp] 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), key_info="".join([self.group[i] for i in candidate.key]), + misc_info=f"p-value was {candidate.p_value}" ) 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]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the caesar cipher alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), "lower": ciphey.iface.ParamSpec( desc="Whether or not the ciphertext should be converted to lowercase first", req=False, default=True, ), "keysize": ciphey.iface.ParamSpec( desc="A key size that should be used. If not given, will attempt to work it out", req=False, ), "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for windowed frequency analysis", req=False, + default=0.5, + ), + "detect_p_value": ciphey.iface.ParamSpec( + desc="The p-value to use for the detection of Vigenere length", + req=False, default=0.01, + ), + "clamp": ciphey.iface.ParamSpec( + desc="The maximum number of candidates that can be returned per key len", + req=False, + default=10, ), } ===========changed ref 2=========== # 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), ) + val = cipheycore.vigenere_detect(analysis, self.expected) + + logger.debug(f"Vigenere has likelihood {val}") + return CrackInfo( + success_likelihood=val, - success_likelihood=cipheycore.vigenere_detect(analysis, self.expected), # TODO: actually calculate runtimes + success_runtime=1e-3, - success_runtime=1e-4, + failure_runtime=1e-2, - 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.detect_p_value), - lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.p_value), ) + + likely_lens_cpy = likely_lens + # Filter out the lens that make no sense + likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] for keysize in likely_lens: # Store the analysis analysis = self.cache.get_or_update( ctext, f"vigenere::{keysize.len}",</s> ===========changed ref 3=========== # module: ciphey.basemods.Crackers.vigenere @registry.register class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: # offset: 1 <s> = 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-3, - success_runtime=2e-4, + failure_runtime=2e-2, - failure_runtime=2e-4, ) + logger.debug(f"Vigenere has likelihood {likely_lens[0].p_value} with lens {[i.len for i in likely_lens]}") + return CrackInfo( + success_likelihood=likely_lens[0].p_value, - success_likelihood=0 * likely_lens[0].p_value, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) ===========changed ref 4=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def recursive_expand(self, node: Node, nested: bool=True) -> None: + if node.depth >= self.max_depth: + return + + logger.trace(f"Expanding depth {node.depth}") + self.expand_decodings(node) # Doing this last allows us to catch simple nested encodings faster if not nested or self.enable_nested: self.expand_crackers(node) ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch class PriorityWorkQueue(Generic[PriorityType, T]): def add_work(self, priority: PriorityType, work: List[T]) -> None: + logger.trace( + f"""Adding work at depth {priority}""" + ) + 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.Searchers.ausearch/AuSearch.getParams
Modified
Ciphey~Ciphey
fd925db8ddbd5959012f1a72fa75aab2d40b63cf
xor ciphers are all fine with no problems whatsover
<13>:<add> default="0"), <del> default="5"),
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> return { <1> "enable_nested": ParamSpec(req=False, <2> desc="Enables nested ciphers. " <3> "Incredibly slow, and not guaranteed to terminate", <4> default="False"), <5> <6> "invert_priority": ParamSpec(req=False, <7> desc="Causes more complex encodings to be looked at first. " <8> "Good for deeply buried encodings.", <9> default="False"), <10> "max_cipher_depth": ParamSpec(req=False, <11> desc="The depth at which we stop trying to crack ciphers. " <12> "Set to 0 to disable", <13> default="5"), <14> "max_depth": ParamSpec(req=False, <15> desc="The depth at which we give up. " <16> "Set to 0 to disable", <17> default="0"), <18> "priority_cap": ParamSpec(req=False, <19> desc="Sets the maximum depth before we give up ordering items.", <20> default="2"), <21> } <22>
===========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')
ciphey.ciphey/main
Modified
Ciphey~Ciphey
cdbbf7240fbd43affcd428fc514657be3921bca3
Merge pull request #379 from Ciphey/bee-san-patch-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, 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>", 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.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["</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.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.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("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"].</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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 3 <s>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.Checkers.ezcheck/EzCheck.check
Modified
Ciphey~Ciphey
cdbbf7240fbd43affcd428fc514657be3921bca3
Merge pull request #379 from Ciphey/bee-san-patch-1
<2>:<add> if res is not None and (self.decider is None or self.decider.check(text)) is not None: <del> if res is not None:
# module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): + def check(self, text: str) -> Optional[str]: - def check(self, text: T) -> Optional[str]: <0> for checker in self.checkers: <1> res = checker.check(text) <2> if res is not None: <3> return res <4> return None <5>
===========unchanged ref 0=========== at: ciphey.basemods.Checkers.ezcheck.EzCheck.__init__ self.checkers: List[Checker[str]] = [] self.decider = None self.decider = config(HumanChecker) at: ciphey.basemods.Checkers.human.HumanChecker check(text: str) -> Optional[str] at: ciphey.iface._modules.Checker check(text: T) -> Optional[str] check(self, text: T) -> Optional[str] ===========changed ref 0=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def check(self, text: str) -> Optional[str]: + with self._config().pause_spinner_handle(): + response = input(f'Result {text.__repr__()} (y/N): ').lower() + if response == "y": + return "" + elif response == "n" or response == "": + return None + else: + return self.check(text) + ===========changed ref 1=========== + # module: ciphey.basemods.Checkers.human + + ===========changed ref 2=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + pass + ===========changed ref 3=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 4=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def getExpectedRuntime(self, text: str) -> float: + return 1 # About a second + ===========changed ref 5=========== # module: ciphey.iface._config class Config: + def set_spinner(self, spinner): + self.objs["spinner"] = spinner + ===========changed ref 6=========== # module: ciphey.iface._config class Config: + def pause_spinner_handle(self): + spinner = self.objs.get("spinner") + + class PausedSpinner: + def __enter__(self): + if spinner is not None: + spinner.stop() + + def __exit__(self, exc_type, exc_val, exc_tb): + if spinner is not None: + spinner.start() + + return PausedSpinner() + ===========changed ref 7=========== <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, 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): """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</s> ===========changed ref 8=========== <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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, 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() # 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</s>
ciphey.basemods.Checkers.ezcheck/EzCheck.getExpectedRuntime
Modified
Ciphey~Ciphey
cdbbf7240fbd43affcd428fc514657be3921bca3
Merge pull request #379 from Ciphey/bee-san-patch-1
<0>:<add> return sum(i.getExpectedRuntime(text) for i in self.checkers) + self.decider.getExpectedRuntime(text) <del> return sum(i.getExpectedRuntime(text) for i in self.checkers)
# module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): def getExpectedRuntime(self, text: T) -> float: <0> return sum(i.getExpectedRuntime(text) for i in self.checkers) <1>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") at: ciphey.iface._modules.Checker getExpectedRuntime(self, text: T) -> float ===========changed ref 0=========== # module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): + def check(self, text: str) -> Optional[str]: - def check(self, text: T) -> Optional[str]: for checker in self.checkers: res = checker.check(text) + if res is not None and (self.decider is None or self.decider.check(text)) is not None: - if res is not None: return res return None ===========changed ref 1=========== + # module: ciphey.basemods.Checkers.human + + ===========changed ref 2=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + pass + ===========changed ref 3=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 4=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def getExpectedRuntime(self, text: str) -> float: + return 1 # About a second + ===========changed ref 5=========== # module: ciphey.iface._config class Config: + def set_spinner(self, spinner): + self.objs["spinner"] = spinner + ===========changed ref 6=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def check(self, text: str) -> Optional[str]: + with self._config().pause_spinner_handle(): + response = input(f'Result {text.__repr__()} (y/N): ').lower() + if response == "y": + return "" + elif response == "n" or response == "": + return None + else: + return self.check(text) + ===========changed ref 7=========== # module: ciphey.iface._config class Config: + def pause_spinner_handle(self): + spinner = self.objs.get("spinner") + + class PausedSpinner: + def __enter__(self): + if spinner is not None: + spinner.stop() + + def __exit__(self, exc_type, exc_val, exc_tb): + if spinner is not None: + spinner.start() + + return PausedSpinner() + ===========changed ref 8=========== <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, 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): """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</s> ===========changed ref 9=========== <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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, 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() # 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</s>
ciphey.basemods.Checkers.ezcheck/EzCheck.__init__
Modified
Ciphey~Ciphey
cdbbf7240fbd43affcd428fc514657be3921bca3
Merge pull request #379 from Ciphey/bee-san-patch-1
<3>:<add> # Disable human checker for automated systems <add> if config.verbosity >= 0: <add> self.decider = config(HumanChecker) <add> else: <add> self.decider = None
# module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): def __init__(self, config: Config): <0> super().__init__(config) <1> <2> self.checkers: List[Checker[str]] = [] <3> <4> # We need to modify the config for each of the objects <5> <6> # First the flag regexes, as they are the fastest <7> flags_config = config <8> flags_config.update_param("regexlist", "resource", "cipheydists::list::flags") <9> # We do not cache, as this uses a different, on-time config <10> self.checkers.append(RegexList(flags_config)) <11> <12> # Next, the json checker <13> self.checkers.append(config(JsonChecker)) <14> <15> # Finally, the Brandon checker, as it is the slowest <16> self.checkers.append(config(Brandon)) <17>
===========unchanged ref 0=========== at: ciphey.basemods.Checkers.human HumanChecker(config: Config) at: ciphey.basemods.Checkers.regex RegexList(config: Config) at: ciphey.iface._config Config() at: ciphey.iface._config.Config update_param(owner: str, name: str, value: Optional[Any]) at: ciphey.iface._config.Config.__init__ self.verbosity: int = 0 at: ciphey.iface._config.Config.update_log_level self.verbosity = verbosity at: ciphey.iface._modules Checker(config: Config) at: ciphey.iface._modules.Checker __init__(config: Config) __init__(self, 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]): def getExpectedRuntime(self, text: T) -> float: + return sum(i.getExpectedRuntime(text) for i in self.checkers) + self.decider.getExpectedRuntime(text) - return sum(i.getExpectedRuntime(text) for i in self.checkers) ===========changed ref 1=========== # module: ciphey.basemods.Checkers.ezcheck @registry.register class EzCheck(Checker[str]): + def check(self, text: str) -> Optional[str]: - def check(self, text: T) -> Optional[str]: for checker in self.checkers: res = checker.check(text) + if res is not None and (self.decider is None or self.decider.check(text)) is not None: - if res is not None: return res return None ===========changed ref 2=========== + # module: ciphey.basemods.Checkers.human + + ===========changed ref 3=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + pass + ===========changed ref 4=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 5=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def getExpectedRuntime(self, text: str) -> float: + return 1 # About a second + ===========changed ref 6=========== # module: ciphey.iface._config class Config: + def set_spinner(self, spinner): + self.objs["spinner"] = spinner + ===========changed ref 7=========== + # module: ciphey.basemods.Checkers.human + @registry.register + class HumanChecker(Checker[str]): + def check(self, text: str) -> Optional[str]: + with self._config().pause_spinner_handle(): + response = input(f'Result {text.__repr__()} (y/N): ').lower() + if response == "y": + return "" + elif response == "n" or response == "": + return None + else: + return self.check(text) + ===========changed ref 8=========== # module: ciphey.iface._config class Config: + def pause_spinner_handle(self): + spinner = self.objs.get("spinner") + + class PausedSpinner: + def __enter__(self): + if spinner is not None: + spinner.stop() + + def __exit__(self, exc_type, exc_val, exc_tb): + if spinner is not None: + spinner.start() + + return PausedSpinner() + ===========changed ref 9=========== <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, 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): """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</s> ===========changed ref 10=========== <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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, 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() # 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</s>
ciphey.iface._config/Config.load_objs
Modified
Ciphey~Ciphey
0f4fbe4ce5774d716dc1439925e39733d9c74cfe
Merge branch 'master' into checker-type-list
<7>:<add> # Checkers do not depend on any other config object <del> # Checkers do not depend on anything <8>:<add> logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") <add> self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) <del> self.objs["checker"] = self(_fwd.registry.get_named(self.checker, Checker))
# module: ciphey.iface._config class Config: def load_objs(self): <0> # Basic type conversion <1> if self.timeout is not None: <2> self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) <3> self.objs["format"] = { <4> key: pydoc.locate(value) for key, value in self.format.items() <5> } <6> <7> # Checkers do not depend on anything <8> self.objs["checker"] = self(_fwd.registry.get_named(self.checker, Checker)) <9> # Searchers only depend on checkers <10> self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher)) <11>
===========changed ref 0=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def getExpectedRuntime(self, text) -> float: + pass + ===========changed ref 1=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + def __call__(self, *args): + return self.check(*args) + ===========changed ref 2=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 3=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def check(self, text) -> Optional[str]: + """Should return some description (or an empty string) on success, otherwise return None""" + pass + ===========changed ref 4=========== # module: ciphey.iface._modules class Checker(Generic[T], ConfigurableModule): + @classmethod + def convert(cls, expected: Set[type]): + class PolyWrapperClass(PolymorphicChecker): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return cls.getParams() + + def check(self, text) -> Optional[str]: + """Should return some description (or an empty string) on success, otherwise return None""" + if type(text) not in expected: + return None + else: + return self._base.check(text) + + def getExpectedRuntime(self, text) -> float: + if type(text) not in expected: + return 0 + else: + return self._base.getExpectedRuntime(text) + + def __init__(self, config: Config): + super().__init__(config) + # This is easier than inheritance + self._base = cls(config) + + PolyWrapperClass.__name__ = cls.__name__ + + return PolyWrapperClass +
ciphey.iface._registry/Registry._register_one
Modified
Ciphey~Ciphey
0f4fbe4ce5774d716dc1439925e39733d9c74cfe
Merge branch 'master' into checker-type-list
<0>:<add> if len(module_args) == 0: <add> self._reg.setdefault(module_base, []).append(input_type) <add> return <add>
# module: ciphey.iface._registry class Registry: def _register_one(self, input_type, module_base, module_args): <0> target_reg = self._reg.setdefault(module_base, {}) <1> # Seek to the given type <2> for subtype in module_args[0:-1]: <3> target_reg = target_reg.setdefault(subtype, {}) <4> target_reg.setdefault(module_args[-1], []).append(input_type) <5>
===========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, PolymorphicChecker} ===========changed ref 0=========== # module: ciphey.iface._registry class Registry: # I was planning on using __init_subclass__, but that is incompatible with dynamic type creation when we have # generic keys 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, PolymorphicChecker} - _modules = {Checker, Cracker, Decoder, ResourceLoader, Searcher} ===========changed ref 1=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def getExpectedRuntime(self, text) -> float: + pass + ===========changed ref 2=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + def __call__(self, *args): + return self.check(*args) + ===========changed ref 3=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 4=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def check(self, text) -> Optional[str]: + """Should return some description (or an empty string) on success, otherwise return None""" + pass + ===========changed ref 5=========== # module: ciphey.iface._config class Config: def load_objs(self): # Basic type conversion if self.timeout is not None: self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) self.objs["format"] = { key: pydoc.locate(value) for key, value in self.format.items() } + # Checkers do not depend on any other config object - # Checkers do not depend on anything + logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") + self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) - self.objs["checker"] = self(_fwd.registry.get_named(self.checker, Checker)) # Searchers only depend on checkers self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher)) ===========changed ref 6=========== # module: ciphey.iface._modules class Checker(Generic[T], ConfigurableModule): + @classmethod + def convert(cls, expected: Set[type]): + class PolyWrapperClass(PolymorphicChecker): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return cls.getParams() + + def check(self, text) -> Optional[str]: + """Should return some description (or an empty string) on success, otherwise return None""" + if type(text) not in expected: + return None + else: + return self._base.check(text) + + def getExpectedRuntime(self, text) -> float: + if type(text) not in expected: + return 0 + else: + return self._base.getExpectedRuntime(text) + + def __init__(self, config: Config): + super().__init__(config) + # This is easier than inheritance + self._base = cls(config) + + PolyWrapperClass.__name__ = cls.__name__ + + return PolyWrapperClass +
ciphey.iface._registry/Registry._real_register
Modified
Ciphey~Ciphey
0f4fbe4ce5774d716dc1439925e39733d9c74cfe
Merge branch 'master' into checker-type-list
<7>:<add> <add> # Replace checker with polymorphic checker <add> if issubclass(input_type, Checker): <add> if len(args) == 0: <add> arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] <add> if len(arg) != 1: <add> raise TypeError(f"No argument for Checker") <add> converted = input_type.convert({arg[0]}) <add> else: <add> converted = input_type.convert(set(args)) <add> return self._real_register(converted) <16>:<add> if len(args) == 0 and hasattr(input_type, "__orig_bases__"): <del> if len(args) == 0: <40>:<add> if module_type is PolymorphicChecker: <add> module_base = PolymorphicChecker <add> elif module_base is None: <del> if module_base is None:
# module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: <0> name = input_type.__name__.lower() <1> name_target = self._names[name] = (input_type, set()) <2> <3> if issubclass(input_type, Targeted): <4> target = input_type.getTarget() <5> else: <6> target = None <7> <8> if issubclass(input_type, Searcher): <9> module_type = module_base = Searcher <10> module_args = () <11> else: <12> module_type: Optional[Type] = None <13> module_base = None <14> <15> # Work out what module type this is <16> if len(args) == 0: <17> for i in input_type.__orig_bases__: <18> if module_type is not None: <19> raise TypeError( <20> f"Type derived from multiple registrable base classes {i} and {module_type}" <21> ) <22> module_base = get_origin(i) <23> if module_base not in self._modules: <24> continue <25> module_type = i <26> else: <27> for i in self._modules: <28> if not issubclass(input_type, i): <29> continue <30> if module_type is not None: <31> raise TypeError( <32> f"Type derived from multiple registrable base classes {i} and {module_type}" <33> ) <34> module_type = i <35> if module_type is None: <36> raise TypeError("No registrable base class") <37> <38> # Now handle the difference between register and register_multi <39> if len(args) == 0: <40> if module_base is None: <41> raise TypeError("No type argument given") <42> self._register_one(input_type, module_base, get_args(module_type)) <43> name_target[1].add(module_base) <44> else: <45> if module_base is not None: <46> raise TypeError(f"Redundant type argument</s>
===========below chunk 0=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 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 ===========unchanged ref 0=========== at: ciphey.iface._modules Targeted() PolymorphicChecker(config: Config) Checker(config: Config) Searcher(config: Config) at: ciphey.iface._registry.Registry _names: Dict[str, Tuple[Type, Set[Type]]] = {} _modules = {Checker, Cracker, Decoder, ResourceLoader, Searcher, PolymorphicChecker} _register_one(input_type, module_base, module_args) _register_one(self, 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') ===========changed ref 0=========== # module: ciphey.iface._registry class Registry: def _register_one(self, input_type, module_base, module_args): + if len(module_args) == 0: + self._reg.setdefault(module_base, []).append(input_type) + return + target_reg = self._reg.setdefault(module_base, {}) # Seek to the given type for subtype in module_args[0:-1]: target_reg = target_reg.setdefault(subtype, {}) target_reg.setdefault(module_args[-1], []).append(input_type) ===========changed ref 1=========== # module: ciphey.iface._registry class Registry: # I was planning on using __init_subclass__, but that is incompatible with dynamic type creation when we have # generic keys 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, PolymorphicChecker} - _modules = {Checker, Cracker, Decoder, ResourceLoader, Searcher} ===========changed ref 2=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def getExpectedRuntime(self, text) -> float: + pass + ===========changed ref 3=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + def __call__(self, *args): + return self.check(*args) + ===========changed ref 4=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 5=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def check(self, text) -> Optional[str]: + """Should return some description (or an empty string) on success, otherwise return None""" + pass + ===========changed ref 6=========== # module: ciphey.iface._config class Config: def load_objs(self): # Basic type conversion if self.timeout is not None: self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) self.objs["format"] = { key: pydoc.locate(value) for key, value in self.format.items() } + # Checkers do not depend on any other config object - # Checkers do not depend on anything + logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") + self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) - self.objs["checker"] = self(_fwd.registry.get_named(self.checker, Checker)) # Searchers only depend on checkers self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher)) ===========changed ref 7=========== # module: ciphey.iface._modules class Checker(Generic[T], ConfigurableModule): + @classmethod + def convert(cls, expected: Set[type]): + class PolyWrapperClass(PolymorphicChecker): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return cls.getParams() + + def check(self, text) -> Optional[str]: + """Should return some description (or an empty string) on success, otherwise return None""" + if type(text) not in expected: + return None + else: + return self._base.check(text) + + def getExpectedRuntime(self, text) -> float: + if type(text) not in expected: + return 0 + else: + return self._base.getExpectedRuntime(text) + + def __init__(self, config: Config): + super().__init__(config) + # This is easier than inheritance + self._base = cls(config) + + PolyWrapperClass.__name__ = cls.__name__ + + return PolyWrapperClass +
ciphey.ciphey/main
Modified
Ciphey~Ciphey
0f4fbe4ce5774d716dc1439925e39733d9c74cfe
Merge branch 'master' into checker-type-list
<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, 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>", 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.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["</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.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.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("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"].</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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 3 <s>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: config.set_spinner(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 + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def getExpectedRuntime(self, text) -> float: + pass + ===========changed ref 1=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + def __call__(self, *args): + return self.check(*args) + ===========changed ref 2=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def __init__(self, config: Config): + super().__init__(config) + ===========changed ref 3=========== # module: ciphey.iface._modules + class PolymorphicChecker(ConfigurableModule): + @abstractmethod + def check(self, text) -> Optional[str]: + """Should return some description (or an empty string) on success, otherwise return None""" + pass + ===========changed ref 4=========== # module: ciphey.iface._registry class Registry: def _register_one(self, input_type, module_base, module_args): + if len(module_args) == 0: + self._reg.setdefault(module_base, []).append(input_type) + return + target_reg = self._reg.setdefault(module_base, {}) # Seek to the given type for subtype in module_args[0:-1]: target_reg = target_reg.setdefault(subtype, {}) target_reg.setdefault(module_args[-1], []).append(input_type) ===========changed ref 5=========== # module: ciphey.iface._registry class Registry: # I was planning on using __init_subclass__, but that is incompatible with dynamic type creation when we have # generic keys 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, PolymorphicChecker} - _modules = {Checker, Cracker, Decoder, ResourceLoader, Searcher}
ciphey.iface._registry/Registry._real_register
Modified
Ciphey~Ciphey
b6f828c2f8af0fb880f8d5376a6d7a518527a916
Made interface even more fluid
<7>:<del> <8>:<del> # Replace checker with polymorphic checker <9>:<del> if issubclass(input_type, Checker): <10>:<del> if len(args) == 0: <11>:<del> arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] <12>:<del> if len(arg) != 1: <13>:<del> raise TypeError(f"No argument for Checker") <14>:<del> converted = input_type.convert({arg[0]}) <15>:<del> else: <16>:<del> converted = input_type.convert(set(args)) <17>:<del> return self._real_register(converted)
# module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: <0> name = input_type.__name__.lower() <1> name_target = self._names[name] = (input_type, set()) <2> <3> if issubclass(input_type, Targeted): <4> target = input_type.getTarget() <5> else: <6> target = None <7> <8> # Replace checker with polymorphic checker <9> if issubclass(input_type, Checker): <10> if len(args) == 0: <11> arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] <12> if len(arg) != 1: <13> raise TypeError(f"No argument for Checker") <14> converted = input_type.convert({arg[0]}) <15> else: <16> converted = input_type.convert(set(args)) <17> return self._real_register(converted) <18> <19> if issubclass(input_type, Searcher): <20> module_type = module_base = Searcher <21> module_args = () <22> else: <23> module_type: Optional[Type] = None <24> module_base = None <25> <26> # Work out what module type this is <27> if len(args) == 0 and hasattr(input_type, "__orig_bases__"): <28> for i in input_type.__orig_bases__: <29> if module_type is not None: <30> raise TypeError( <31> f"Type derived from multiple registrable base classes {i} and {module_type}" <32> ) <33> module_base = get_origin(i) <34> if module_base not in self._modules: <35> continue <36> module_type = i <37> else: <38> for i in self._modules: <39> if not issubclass(input_type, i): <40> continue <41> if module_type is not None: <42> raise TypeError( <43> f"Type derived from multiple registrable base classes {i} and</s>
===========below chunk 0=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 ) 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_type is PolymorphicChecker: module_base = PolymorphicChecker elif 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: # 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() PolymorphicChecker(config: Config) Checker(config: Config) 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, PolymorphicChecker} _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.iface._config/Config.__init__
Modified
Ciphey~Ciphey
172472e457a9e15db204901d14cddf09bdd529a8
Fixed byte typing
<3>:<add> self.format: str = "str" <del> self.format: Dict[str, str] = {"in": "str", "out": "str"}
# module: ciphey.iface._config class Config: def __init__(self): <0> self.verbosity: int = 0 <1> self.searcher: str = "ausearch" <2> self.params: Dict[str, Dict[str, Union[str, List[str]]]] = {} <3> self.format: Dict[str, str] = {"in": "str", "out": "str"} <4> self.modules: List[str] = [] <5> self.checker: str = "ezcheck" <6> self.default_dist: str = "cipheydists::dist::english" <7> self.timeout: Optional[int] = None <8> self._inst: Dict[type, Any] = {} <9> self.objs: Dict[str, Any] = {} <10> self.cache: Cache = Cache() <11>
ciphey.iface._config/Config.update_format
Modified
Ciphey~Ciphey
172472e457a9e15db204901d14cddf09bdd529a8
Fixed byte typing
<1>:<add> self.format = value <del> self.format[paramname] = value
# module: ciphey.iface._config class Config: + def update_format(self, value: Optional[str]): - def update_format(self, paramname: str, value: Optional[Any]): <0> if value is not None: <1> self.format[paramname] = value <2>
===========changed ref 0=========== # 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: str = "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()
ciphey.iface._config/Config.load_objs
Modified
Ciphey~Ciphey
172472e457a9e15db204901d14cddf09bdd529a8
Fixed byte typing
<3>:<del> self.objs["format"] = { <4>:<del> key: pydoc.locate(value) for key, value in self.format.items() <5>:<del> } <6>:<add> self.objs["format"] = pydoc.locate(self.format)
# module: ciphey.iface._config class Config: def load_objs(self): <0> # Basic type conversion <1> if self.timeout is not None: <2> self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) <3> self.objs["format"] = { <4> key: pydoc.locate(value) for key, value in self.format.items() <5> } <6> <7> # Checkers do not depend on any other config object <8> logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") <9> self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) <10> # Searchers only depend on checkers <11> self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher)) <12>
===========changed ref 0=========== # module: ciphey.iface._config class Config: + def update_format(self, value: Optional[str]): - def update_format(self, paramname: str, value: Optional[Any]): if value is not None: + self.format = value - self.format[paramname] = value ===========changed ref 1=========== # 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: str = "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()
ciphey.ciphey/main
Modified
Ciphey~Ciphey
172472e457a9e15db204901d14cddf09bdd529a8
Fixed byte typing
<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, 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>", 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.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["</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.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.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") # 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"]["in"] != bytes: kwargs["text"] = kwargs["text"].decode("utf-8") elif kwargs["text_stdin"] is not None: kwargs["</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.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_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: config.set_spinner(sp) result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result) ===========changed ref 0=========== # module: ciphey.iface._config class Config: + def update_format(self, value: Optional[str]): - def update_format(self, paramname: str, value: Optional[Any]): if value is not None: + self.format = value - self.format[paramname] = value ===========changed ref 1=========== # 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: str = "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 2=========== # module: ciphey.iface._config class Config: def load_objs(self): # Basic type conversion if self.timeout is not None: self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) - self.objs["format"] = { - key: pydoc.locate(value) for key, value in self.format.items() - } + self.objs["format"] = pydoc.locate(self.format) # Checkers do not depend on any other config object logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) # Searchers only depend on checkers self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher))
ciphey.basemods.Searchers.ausearch/Node.decoding
Modified
Ciphey~Ciphey
172472e457a9e15db204901d14cddf09bdd529a8
Fixed byte typing
<4>:<del> target_type: type = config.objs["format"]["out"] <14>:<del> if type(result) == target_type: <15>:<add> check_res = checker(result) <del> check_res = checker(result) <16>:<add> if check_res is not None: <del> if check_res is not None: <17>:<add> raise AuSearchSuccessful(target=ret, info=check_res) <del> raise AuSearchSuccessful(target=ret, info=check_res)
# module: ciphey.basemods.Searchers.ausearch @dataclass class Node: @staticmethod def decoding( config: Config, route: Union[Cracker, Decoder], result: Any, source: "Node" ) -> "Node": <0> if not config.cache.mark_ctext(result): <1> raise DuplicateNode() <2> <3> checker: Checker = config.objs["checker"] <4> target_type: type = config.objs["format"]["out"] <5> ret = Node( <6> parent=None, <7> level=SearchLevel( <8> name=type(route).__name__.lower(), result=CrackResult(value=result) <9> ), <10> depth=source.depth + 1, <11> ) <12> edge = Edge(source=source, route=route, dest=ret) <13> ret.parent = edge <14> if type(result) == target_type: <15> check_res = checker(result) <16> if check_res is not None: <17> raise AuSearchSuccessful(target=ret, info=check_res) <18> return ret <19>
===========changed ref 0=========== # module: ciphey.iface._config class Config: + def update_format(self, value: Optional[str]): - def update_format(self, paramname: str, value: Optional[Any]): if value is not None: + self.format = value - self.format[paramname] = value ===========changed ref 1=========== # 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: str = "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 2=========== # module: ciphey.iface._config class Config: def load_objs(self): # Basic type conversion if self.timeout is not None: self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) - self.objs["format"] = { - key: pydoc.locate(value) for key, value in self.format.items() - } + self.objs["format"] = pydoc.locate(self.format) # Checkers do not depend on any other config object logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) # Searchers only depend on checkers self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher)) ===========changed ref 3=========== <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, 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): """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</s> ===========changed ref 4=========== <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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, 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() # 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</s> ===========changed ref 5=========== <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.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.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"] is not None: - if kwargs["bytes_input"] is not None: + config.update_format("bytes") - 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"]["in"] != bytes: - kwargs["text"] =</s>
ciphey.basemods.Searchers.ausearch/AuSearch.search
Modified
Ciphey~Ciphey
172472e457a9e15db204901d14cddf09bdd529a8
Fixed byte typing
<9>:<del> if type(ctext) == self._config().objs["format"]["out"]: <10>:<add> check_res = self._config().objs["checker"](ctext) <del> check_res = self._config().objs["checker"](ctext) <11>:<add> if check_res is not None: <del> if check_res is not None: <12>:<add> return SearchResult(check_res=check_res, path=[root.level]) <del> return SearchResult(check_res=check_res, path=[root.level])
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: <0> logger.trace( <1> f"""Beginning AuSearch with {"inverted" if self.invert_priority else "normal"} priority""" <2> ) <3> <4> try: <5> root = Node.root(self._config(), ctext) <6> except DuplicateNode: <7> return None <8> <9> if type(ctext) == self._config().objs["format"]["out"]: <10> check_res = self._config().objs["checker"](ctext) <11> if check_res is not None: <12> return SearchResult(check_res=check_res, path=[root.level]) <13> <14> try: <15> self.recursive_expand(root, False) <16> <17> while True: <18> if self.work.empty(): <19> break <20> # Get the highest level result <21> chunk = self.work.get_work_chunk() <22> infos = [i.info for i in chunk] <23> # Work through all of this level's results <24> while len(chunk) != 0: <25> max_depth = 0 <26> for i in chunk: <27> if i.source.depth > max_depth: <28> max_depth = i.source.depth <29> logger.debug(f"At depth {chunk[0].source.depth}") <30> <31> # if self.disable_priority: <32> # chunk += self.work.get_work_chunk() <33> # infos = [i.info for i in chunk] <34> <35> logger.trace(f"{len(infos)} remaining on this level") <36> step_res = cipheycore.ausearch_minimise(infos) <37> edge: Edge = chunk.pop(step_res.index) <38> logger.trace( <39> f"Weight is currently {step_res.weight} " <40> f"when we pick {type(edge.route).__name__.lower()} " </s>
===========below chunk 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 ) 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( 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") ===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @dataclass class Node: @staticmethod def decoding( config: Config, route: Union[Cracker, Decoder], result: Any, source: "Node" ) -> "Node": if not config.cache.mark_ctext(result): raise DuplicateNode() checker: Checker = config.objs["checker"] - target_type: type = config.objs["format"]["out"] ret = Node( parent=None, level=SearchLevel( name=type(route).__name__.lower(), result=CrackResult(value=result) ), depth=source.depth + 1, ) edge = Edge(source=source, route=route, dest=ret) ret.parent = edge - if type(result) == target_type: + check_res = checker(result) - check_res = checker(result) + if check_res is not None: - if check_res is not None: + raise AuSearchSuccessful(target=ret, info=check_res) - raise AuSearchSuccessful(target=ret, info=check_res) return ret ===========changed ref 1=========== # module: ciphey.iface._config class Config: + def update_format(self, value: Optional[str]): - def update_format(self, paramname: str, value: Optional[Any]): if value is not None: + self.format = value - self.format[paramname] = value ===========changed ref 2=========== # 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: str = "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 3=========== # module: ciphey.iface._config class Config: def load_objs(self): # Basic type conversion if self.timeout is not None: self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) - self.objs["format"] = { - key: pydoc.locate(value) for key, value in self.format.items() - } + self.objs["format"] = pydoc.locate(self.format) # Checkers do not depend on any other config object logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) # Searchers only depend on checkers self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher)) ===========changed ref 4=========== <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, 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): """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</s>
ciphey.basemods.Searchers.ausearch/AuSearch.__init__
Modified
Ciphey~Ciphey
172472e457a9e15db204901d14cddf09bdd529a8
Fixed byte typing
<2>:<del> self._target_type: type = config.objs["format"]["out"]
# 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.priority_cap = int(self._params()["priority_cap"]) <6> self.enable_nested = bool(distutils.util.strtobool(self._params()["enable_nested"])) <7> self.max_cipher_depth = int(self._params()["max_cipher_depth"]) <8> if self.max_cipher_depth == 0: <9> self.max_cipher_depth = math.inf <10> self.max_depth = int(self._params()["max_depth"]) <11> if self.max_depth == 0: <12> self.max_depth = math.inf <13>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @dataclass class Node: @staticmethod def decoding( config: Config, route: Union[Cracker, Decoder], result: Any, source: "Node" ) -> "Node": if not config.cache.mark_ctext(result): raise DuplicateNode() checker: Checker = config.objs["checker"] - target_type: type = config.objs["format"]["out"] ret = Node( parent=None, level=SearchLevel( name=type(route).__name__.lower(), result=CrackResult(value=result) ), depth=source.depth + 1, ) edge = Edge(source=source, route=route, dest=ret) ret.parent = edge - if type(result) == target_type: + check_res = checker(result) - check_res = checker(result) + if check_res is not None: - if check_res is not None: + raise AuSearchSuccessful(target=ret, info=check_res) - raise AuSearchSuccessful(target=ret, info=check_res) return ret ===========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) - check_res = self._config().objs["checker"](ctext) + if check_res is not None: - if check_res is not None: + return SearchResult(check_res=check_res, path=[root.level]) - return SearchResult(check_res=check_res, path=[root.level]) try: self.recursive_expand(root, False) 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: max_depth = 0 for i in chunk: if i.source.depth > max_depth: max_depth = i.source.depth logger.debug(f"At depth {chunk[0].source.depth}") # if self.disable_priority: # chunk += self.work.get_work_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 {</s> ===========changed ref 2=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def search(self, ctext: Any) -> Optional[SearchResult]: # offset: 1 <s>) logger.trace( f"Weight is currently {step_res.weight} " f"when we pick {type(edge.route).__name__.lower()} " f"with depth {edge.source.depth}" ) 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( 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") ===========changed ref 3=========== # module: ciphey.iface._config class Config: + def update_format(self, value: Optional[str]): - def update_format(self, paramname: str, value: Optional[Any]): if value is not None: + self.format = value - self.format[paramname] = value ===========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: str = "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 Config: def load_objs(self): # Basic type conversion if self.timeout is not None: self.objs["timeout"] = datetime.timedelta(seconds=int(self.timeout)) - self.objs["format"] = { - key: pydoc.locate(value) for key, value in self.format.items() - } + self.objs["format"] = pydoc.locate(self.format) # Checkers do not depend on any other config object logger.trace(f"Registry is {_fwd.registry._reg[PolymorphicChecker]}") self.objs["checker"] = self(_fwd.registry.get_named(self.checker, PolymorphicChecker)) # Searchers only depend on checkers self.objs["searcher"] = self(_fwd.registry.get_named(self.searcher, Searcher))
ciphey.basemods.Searchers.ausearch/Node.cracker
Modified
Ciphey~Ciphey
dfa772437c70b43f9904cc1985ab555e354d9f6f
missed one!
<4>:<del> target_type: type = config.objs["format"]["out"] <13>:<del> if type(result.value) == target_type: <14>:<add> check_res = checker(result.value) <del> check_res = checker(result.value) <15>:<add> if check_res is not None: <del> if check_res is not None: <16>:<add> raise AuSearchSuccessful(target=ret, info=check_res) <del> raise AuSearchSuccessful(target=ret, info=check_res)
# module: ciphey.basemods.Searchers.ausearch @dataclass class Node: @staticmethod def cracker(config: Config, edge_template: "Edge", result: CrackResult) -> "Node": <0> if not config.cache.mark_ctext(result.value): <1> raise DuplicateNode() <2> <3> checker: Checker = config.objs["checker"] <4> target_type: type = config.objs["format"]["out"] <5> # Edges do not directly contain containers, so this is fine <6> edge = copy(edge_template) <7> ret = Node( <8> parent=edge, <9> level=SearchLevel(name=type(edge.route).__name__.lower(), result=result), <10> depth=edge.source.depth + 1, <11> ) <12> edge.dest = ret <13> if type(result.value) == target_type: <14> check_res = checker(result.value) <15> if check_res is not None: <16> raise AuSearchSuccessful(target=ret, info=check_res) <17> return ret <18>
ciphey.basemods.Checkers.brandon/Brandon.checker
Modified
Ciphey~Ciphey
2ed33227931ac9fb04b34a80169d5b25eb005305
fixed brandon checker
<25>:<add> if text_length <= 0: <add> return False
# 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.basemods.Checkers.brandon/Brandon.check
Modified
Ciphey~Ciphey
2ed33227931ac9fb04b34a80169d5b25eb005305
fixed brandon checker
<15>:<add> logger.trace("Returning None from Brandon as the text cleaned is none.") <19>:<del> # "Phase 1": {0: {"check": 0.02}, 110: {"stop": 0.15}, 150: {"stop": 0.28}} <20>:<del> <21>:<del> # Phase 1 checking
# 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(self.thresholds_phase1) <31> what_to_use = self.thresholds_phase1[str(what_to_use)] <32> # def checker(self, text: str, threshold: float, text_length: int, var: set) -> bool: <33> if "check" in what_to_use: <34> # perform check 1k words <35> result = self.checker( <36> text, what_to_use["check"], length_text, self.top1000Words <37> )</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 elif "stop" in what_to_use: # perform stopwords result = self.checker( text, what_to_use["stop"], length_text, self.stopwords ) elif "dict" in what_to_use: 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) return "" if result else None ===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon clean_text(text: str) -> set checker(self, text: str, threshold: float, text_length: int, var: set) -> bool checker(text: str, threshold: float, text_length: int, var: set) -> bool 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"]) self.stopwords = config.get_resource(self._params().get("stopwords")) at: ciphey.iface._modules.Checker check(self, text: T) -> Optional[str] ===========changed ref 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: """Given text determine if it passes checker The checker uses the vairable passed to it. I.E. Stopwords list, 1k words, dictionary Args: text -> The text to check threshold -> at what point do we return True? The percentage of text that is in var before we return True text_length -> the length of the text var -> the variable we are checking against. Stopwords list, 1k words list, dictionray list. Returns: boolean -> True for it passes the test, False for it fails the test.""" if text is None: logger.trace(f"Checker's text is None, so returning False") return False if var is None: logger.trace(f"Checker's input var is None, so returning False") return False percent = ceil(text_length * threshold) logger.trace(f"Checker's chunks are size {percent}") meet_threshold = 0 location = 0 end = percent while location <= text_length: + if text_length <= 0: + return False # chunks the text, so only gets THRESHOLD chunks of text at a time text = list(text) to_analyse = text[location:end] logger.trace(f"To analyse is {to_analyse}") for word in to_analyse: # if word is a stopword, + 1 to the counter if word in var: logger.trace( f"{word} is in var, which means I am +=1 to the meet_threshold which is {meet_threshold}" ) meet_threshold += 1 </s> ===========changed ref 1=========== # 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 <s> I am +=1 to the meet_threshold which is {meet_threshold}" ) 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
ciphey.basemods.Checkers.brandon/Brandon.checker
Modified
Ciphey~Ciphey
6d7c58383081f9f82eebebc0fbb9490b12efc11e
extracted from loop
<24>:<add> if text_length <= 0: <add> return False <add> <25>:<del> if text_length <= 0: <26>:<del> return False
# 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> if text_length <= 0: <26> return False <27> # chunks the text, so only gets THRESHOLD chunks of text at a time <28> text = list(text) <29> to_analyse = text[location:end] <30> logger.trace(f"To analyse is {to_analyse}") <31> for word in to_analyse: <32> # if word is a stopword, + 1 to the counter <33> if word in var: <34> logger.trace( <35> f"{word} is in</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.basemods.Checkers.entropy/Enttropy.check
Modified
Ciphey~Ciphey
877600a9429874039afde8903ac3c37b88e5bc1e
edited templates
<0>:<add> logger.trace(f"Trying entropy checker") <del> logger.trace(f"Trying json checker") <1>:<add> pass <2>:<del> try: <3>:<del> json.loads(text) <4>:<del> return "" <5>:<del> except ValueError: <6>:<del> return None <7>:<del>
# module: ciphey.basemods.Checkers.entropy @registry.register class Enttropy(Checker[str]): def check(self, text: T) -> Optional[str]: <0> logger.trace(f"Trying json checker") <1> <2> try: <3> json.loads(text) <4> return "" <5> except ValueError: <6> return None <7>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") at: ciphey.iface._modules.Checker check(self, text: T) -> Optional[str] getExpectedRuntime(self, text: T) -> float
ciphey.basemods.Checkers.entropy/Enttropy.getExpectedRuntime
Modified
Ciphey~Ciphey
877600a9429874039afde8903ac3c37b88e5bc1e
edited templates
<1>:<add> # Uses benchmark from Discord <add> return 2e-7 * len(text) <del> return 1e-7 * len(text) # From benchmarks I found online
# module: ciphey.basemods.Checkers.entropy @registry.register class Enttropy(Checker[str]): def getExpectedRuntime(self, text: T) -> float: <0> # TODO: actually bench this <1> return 1e-7 * len(text) # From benchmarks I found online <2>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._modules.Checker __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.basemods.Checkers.entropy @registry.register class Enttropy(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace(f"Trying entropy checker") - logger.trace(f"Trying json checker") + pass - try: - json.loads(text) - return "" - except ValueError: - return None -
ciphey.basemods.Checkers.format/JsonChecker.check
Modified
Ciphey~Ciphey
c549e54b4d00bc66209f8222a54487637834041a
Merge branch 'master' into bee-389
<1>:<add> <add> # https://github.com/Ciphey/Ciphey/issues/389 <add> if text.isdigit(): <add> return None
# module: ciphey.basemods.Checkers.format @registry.register class JsonChecker(Checker[str]): def check(self, text: T) -> Optional[str]: <0> logger.trace(f"Trying json checker") <1> <2> try: <3> json.loads(text) <4> return "" <5> except ValueError: <6> return None <7>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") at: ciphey.iface._modules.Checker check(self, text: T) -> Optional[str]
tests.test_main/test_base69
Modified
Ciphey~Ciphey
c549e54b4d00bc66209f8222a54487637834041a
Merge branch 'master' into bee-389
<2>:<add> "192848183123171", <del> "kAZAtABBeB8A-AoB8ADBNAhBLA1AFBgA0AXBfBGATAVAFBgAwAWBHB<ACAkA-AnB0AVBnBNBDARAZBiBQAYAtAhBhABA<ArB4AbAMANBDAFAXBfBQAdAOAmArAUAAA2=", <4>:<add> assert res != "192848183123171" <del> assert res == answer_str
# module: tests.test_main def test_base69(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "kAZAtABBeB8A-AoB8ADBNAhBLA1AFBgA0AXBfBGATAVAFBgAwAWBHB<ACAkA-AnB0AVBnBNBDARAZBiBQAYAtAhBhABA<ArB4AbAMANBDAFAXBfBQAdAOAmArAUAAA2=", <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" ===========changed ref 0=========== # module: ciphey.basemods.Checkers.format @registry.register class JsonChecker(Checker[str]): def check(self, text: T) -> Optional[str]: logger.trace(f"Trying json checker") + + # https://github.com/Ciphey/Ciphey/issues/389 + if text.isdigit(): + return None try: json.loads(text) return "" except ValueError: return None
tests.test_main/test_base69
Modified
Ciphey~Ciphey
5e51238419580897c186a67f6ae0ec38f1d6c4e9
Merge branch 'bee-389' of github.com:Ciphey/Ciphey into bee-389
<2>:<add> "0110100001100101011011000110110001101111", <del> "192848183123171", <4>:<add> assert res != "0110100001100101011011000110110001101111" <del> assert res != "192848183123171"
# module: tests.test_main def test_base69(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "192848183123171", <3> ) <4> assert res != "192848183123171" <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()
ciphey.ciphey/main
Modified
Ciphey~Ciphey
3097c828d898566c76bebd4e01d015fcd8c95283
Merge branch 'master' into ohnoimessedup
<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, 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>", 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.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["</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.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.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"] is not None: config.update_format("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() 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.</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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 3 <s> 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 config.objs["format"] == str and type(kwargs["text"]) is bytes: kwargs["text"] = kwargs["text"].decode("utf-8") elif config.objs["format"] == bytes and type(kwargs["text"]) is str: kwargs["text"] = kwargs["text"].encode("utf-8") else: raise TypeError(f"Cannot load type {config.format}") 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: config.set_spinner(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.Decoders.dna/Dna.decode
Modified
Ciphey~Ciphey
63c80f0b28f875691260c625165f206c6175ea2e
Update dna.py
<8>:<add> dna_keys = self.DNA_DICT.keys() <9>:<del> try: <10>:<add> for i in ctext_split: <del> for i in ctext_split: <11>:<add> if i in dna_keys: <12>:<add> else: <add> return None <add> logger.debug(f"DNA successful, returning '{ctext_decoded}'") <del> logger.debug(f"DNA decoded string is {ctext_decoded}") <13>:<add> return ctext_decoded <del> return ctext_decoded <14>:<del> except Exception: <15>:<del> return None
# module: ciphey.basemods.Decoders.dna @registry.register class Dna(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Performs DNA decoding <2> """ <3> logger.trace("Attempting DNA decoder") <4> ctext_decoded = "" <5> ctext = re.sub(r"[,;:\-\s]", "", ctext) <6> ctext = " ".join(ctext[i : i + 3] for i in range(0, len(ctext), 3)) <7> ctext_split = ctext.split(" ") <8> <9> try: <10> for i in ctext_split: <11> ctext_decoded += self.DNA_DICT[i] <12> logger.debug(f"DNA decoded string is {ctext_decoded}") <13> return ctext_decoded <14> except Exception: <15> return None <16>
===========unchanged ref 0=========== at: ciphey.basemods.Decoders.dna.Dna.__init__ self.DNA_DICT = config.get_resource(self._params()["dict"], Translation) at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] at: re sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr
ciphey.basemods.Decoders.morse/MorseCode.decode
Modified
Ciphey~Ciphey
7334614bbc29c8064f7a1172208e1d2e0d158ea7
Fixed morse
<0>:<del> # Trim end <1>:<del> while text[-1] in self.BOUNDARIES: <2>:<del> text = text[:-1] <3>:<del> <14>:<add> if i in self.ALLOWED: <add> continue <32>:<add> f"Char boundary is unicode {ord(char_boundary)}, and word boundary is unicode {ord(word_boundary) if word_boundary is not None else None}" <del> f"'Char boundary is '{char_boundary}', and word boundary is '{word_boundary}'" <40>:<add> char = char.translate(self.PURGE) <add> if len(char) == 0: <add> continue <43>:<add> logger.trace(f"Invalid codeword '{char}' found") <del> logger.trace(f"Invalid codeword '{word}' found")
# module: ciphey.basemods.Decoders.morse @registry.register class MorseCode(ciphey.iface.Decoder[str, str]): def decode(self, text: str) -> Optional[str]: <0> # Trim end <1> while text[-1] in self.BOUNDARIES: <2> text = text[:-1] <3> <4> logger.trace("Attempting morse code") <5> <6> char_boundary = word_boundary = None <7> <8> char_boundary = word_boundary = None <9> char_priority = word_priority = 0 <10> # Custom loop allows early break <11> for i in text: <12> i_priority = self.BOUNDARIES.get(i) <13> if i_priority is None: <14> logger.trace(f"Non-morse char '{i}' found") <15> return None <16> <17> if i_priority <= char_priority or i == char_boundary or i == word_boundary: <18> continue <19> # Default to having a char boundary over a word boundary <20> if ( <21> i_priority > word_priority <22> and word_boundary is None <23> and char_boundary is not None <24> ): <25> word_priority = i_priority <26> word_boundary = i <27> continue <28> char_priority = i_priority <29> char_boundary = i <30> <31> logger.trace( <32> f"'Char boundary is '{char_boundary}', and word boundary is '{word_boundary}'" <33> ) <34> <35> result = "" <36> <37> for word in text.split(word_boundary) if word_boundary else [text]: <38> logger.trace(f"Attempting to decode word {word}") <39> for char in word.split(char_boundary): <40> try: <41> m = self.MORSE_CODE_DICT_INV[char] <42> except KeyError: <43> logger.trace(f"Invalid codeword '{word}' found") <44> return None <45> result = result + m <46> # after every word add a space <47> result = result + " " </s>
===========below chunk 0=========== # module: ciphey.basemods.Decoders.morse @registry.register class MorseCode(ciphey.iface.Decoder[str, str]): def decode(self, text: str) -> Optional[str]: # offset: 1 logger.trace(f"Morse code failed to match") return None # Remove trailing space result = result[:-1] logger.debug(f"Morse code successful, returning {result}") return result.strip().upper() ===========unchanged ref 0=========== at: ciphey.basemods.Decoders.morse.MorseCode BOUNDARIES = {" ": 1, "/": 2, "\n": 3} PURGE = {ord(c): None for c in BOUNDARIES.keys()} MAX_PRIORITY = 3 ALLOWED = {".", "-", " ", "/", "\n"} MORSE_CODE_DICT: Dict[str, str] MORSE_CODE_DICT_INV: Dict[str, str] at: ciphey.basemods.Decoders.morse.MorseCode.__init__ self.MORSE_CODE_DICT_INV = {v: k for k, v in self.MORSE_CODE_DICT.items()} at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: ciphey.basemods.Decoders.morse @registry.register class MorseCode(ciphey.iface.Decoder[str, str]): # A priority list for char/word boundaries + BOUNDARIES = {" ": 1, "/": 2, "\n": 3} - BOUNDARIES = {" ": 1, "/": 2, "\n": 3, ".": -1, "-": -1} + PURGE = {ord(c): None for c in BOUNDARIES.keys()} MAX_PRIORITY = 3 ALLOWED = {".", "-", " ", "/", "\n"} MORSE_CODE_DICT: Dict[str, str] MORSE_CODE_DICT_INV: Dict[str, str]
ciphey.basemods.Decoders.url/Url.decode
Modified
Ciphey~Ciphey
a322ba1d7af3553ab0a4b9c18a4563afd05b7271
Fix issues
<3>:<del> ctext = ctext.replace("+", " ") # Replace + sign with a space for unquote <5>:<add> result = unquote_plus(ctext, errors="strict") <del> result = unquote(ctext) # Built-in function that decodes URL encoding
# module: ciphey.basemods.Decoders.url @registry.register class Url(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Performs URL decoding <2> """ <3> ctext = ctext.replace("+", " ") # Replace + sign with a space for unquote <4> try: <5> result = unquote(ctext) # Built-in function that decodes URL encoding <6> if result != ctext: <7> return result <8> else: <9> return None <10> except Exception: <11> return None <12>
ciphey.basemods.Checkers.brandon/Brandon.calculateWhatChecker
Modified
Ciphey~Ciphey
fc854ecf37b688832f25cdec094bcada739bfae3
Object is not subscriptable error fix (#440)
<18>:<add> what_to_use = list(key)[_keys.index(_keys[-1])] <del> what_to_use = key[_keys[-1]]
# 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> # [0, 110, 150] <23> if i <= length_text: <24> what_to_use = i <25> return what_to_use <26>
===========unchanged ref 0=========== at: ciphey.basemods.Checkers.brandon.Brandon wordlist: set
ciphey.basemods.Decoders.baudot/Baudot.decode
Modified
Ciphey~Ciphey
305b09ac1d45aa6620f5f8b82a5aa8e64c7605ef
Merge branch 'master' into master
<0>:<del> """Write the code that decodes here <1>:<del> ctext -> the input to the function <2>:<del> returns string <3>:<del> """ <4>:<del> <5>:<del>
# module: ciphey.basemods.Decoders.baudot @registry.register_multi((str, str), (bytes, bytes)) class Baudot(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """Write the code that decodes here <1> ctext -> the input to the function <2> returns string <3> """ <4> <5> <6> ret = "" <7> switch_to_digit_map = 0 <8> if type(ctext) == str: <9> if re.search("^[01]{5}$", ctext.split()[0]): <10> for i in ctext.split(): <11> if i == "11011": <12> switch_to_digit_map = 1 <13> if i == "11111": <14> switch_to_digit_map = 0 <15> if switch_to_digit_map == 1: <16> ret += self.BAUDOT_DICT["+" + i] <17> if switch_to_digit_map == 0: <18> ret += self.BAUDOT_DICT[i] <19> return ret <20> else: <21> return None <22>
===========unchanged ref 0=========== at: ciphey.basemods.Decoders.baudot.Baudot.__init__ self.BAUDOT_DICT = config.get_resource(self._params()["dict"], Translation) at: ciphey.iface._config Config() at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] priority() -> float __init__(self, config: Config) at: re search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] search(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] ===========changed ref 0=========== # module: ciphey.basemods.Decoders.morse @registry.register class MorseCode(ciphey.iface.Decoder[str, str]): - @staticmethod - def getName() -> str: - return "morse" -
ciphey.basemods.Decoders.brainfuck/Brainfuck.decode
Modified
Ciphey~Ciphey
ce7f234cea0b44d738d0f5d1bc84382614145019
Cleaned up some things
<12>:<add> (excluding ",") and whitespace <del> (excluding ",") and whitespace (tabs, spaces, and newlines) <20>:<add> logger.trace("Attempting brainfuck") <add> <22>:<add> codeptr, memptr = 0, 0 # Instruction pointer and stack pointer <del> codeptr, memptr = 0, 0 # instruction pointer, stack pointer <23>:<add> timelimit = 60 # The timeout in seconds <del> timelimit = 60 # timeout, in seconds <27>:<add> # If it doesn't appear to be valid brainfuck code <del> # this doesn't appear to be a brainfuck program we can decode <29>:<add> logger.trace("Failed to interpret brainfuck due to invalid characters") <del> logger.debug("Sample is not Ciphey-legal brainfuck. Continuing...") <32>:<add> # Get start time <del> # get start time <39>:<add> # Return none if we've been running for over a minute <del> # arbitrarily quit if we've been running for over a minute <41>:<add> logger.trace("Failed to interpret brainfuck due to timing out") <del> logger.trace("Brainfuck decoding timed out")
# module: ciphey.basemods.Decoders.brainfuck @registry.register class Brainfuck(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Takes a ciphertext and treats it as a Brainfuck program, <2> interpreting it and saving the output as a string to return. <3> <4> Brainfuck is a very simple, Turing-complete esoteric language. <5> Below is a simplified interpreter that attempts to check whether a <6> given ciphertext is a brainfuck program that would output a string. <7> <8> A program that can be "decoded" like this is one that: <9> * Does not require user input ("," instruction) <10> * Includes at least one putchar instruction (".") <11> * Does not contain anything but the main 7 instructions, <12> (excluding ",") and whitespace (tabs, spaces, and newlines) <13> <14> Details: <15> * This implementation wraps the memory pointer for ">" and "<" <16> * It is time-limited to 60 seconds, to prevent hangups <17> * The program starts with 100 memory cells, chosen arbitrarily <18> """ <19> <20> result = "" <21> memory = [0] * 100 <22> codeptr, memptr = 0, 0 # instruction pointer, stack pointer <23> timelimit = 60 # timeout, in seconds <24> <25> bracemap, isbf = self.bracemap_and_check(ctext) <26> <27> # this doesn't appear to be a brainfuck program we can decode <28> if not isbf: <29> logger.debug("Sample is not Ciphey-legal brainfuck. Continuing...") <30> return None <31> <32> # get start time <33> start = time.time() <34> <35> while codeptr < len(ctext): <36> <37> current = time.time() <38> <39> # arbitrarily quit if we've been running for over a minute <40> if current - start > timelimit: <41> logger.trace("Brainfuck decoding timed out") <42> return None <43> </s>
===========below chunk 0=========== # module: ciphey.basemods.Decoders.brainfuck @registry.register class Brainfuck(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: # offset: 1 if cmd == "+": if memory[memptr] < 255: memory[memptr] = memory[memptr] + 1 else: memory[memptr] = 0 elif cmd == "-": if memory[memptr] > 0: memory[memptr] = memory[memptr] - 1 else: memory[memptr] = 255 elif cmd == ">": if memptr == len(memory) - 1: memory.append(0) memptr += 1 elif cmd == "<": if memptr == 0: memptr = len(memory) - 1 else: memptr -= 1 # if we're at the beginning of the loop and the memory is 0, # exit the loop elif cmd == "[" and memory[memptr] == 0: codeptr = bracemap[codeptr] # if we're at the end of the loop and the memory is >0, jmp to # the beginning of the loop elif cmd == "]" and memory[memptr]: codeptr = bracemap[codeptr] # store the output as a string instead of printing it out elif cmd == ".": result += chr(memory[memptr]) codeptr += 1 return result ===========unchanged ref 0=========== at: ciphey.basemods.Decoders.brainfuck.Brainfuck bracemap_and_check(program: str) -> Tuple[Optional[Dict], bool] at: ciphey.iface._fwd registry = None at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") Decoder(config: Config) at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] at: time time() -> float
ciphey.basemods.Crackers.rot47/Rot47.attemptCrack
Modified
Ciphey~Ciphey
49bd1c15469cbf1e98e3d09700d9e86cb6da9ae7
Clean up some things
<19>:<add> logger.trace("Filtering for better results") <del> logger.trace(f"Filtering for better results")
# module: ciphey.basemods.Crackers.rot47 @registry.register class Rot47(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> logger.debug(f"Trying ROT47 cipher on {ctext}") <1> <2> logger.trace("Beginning cipheycore simple analysis") <3> <4> # Hand it off to the core <5> analysis = self.cache.get_or_update( <6> ctext, <7> "cipheycore::simple_analysis", <8> lambda: cipheycore.analyse_string(ctext), <9> ) <10> logger.trace("Beginning cipheycore::caesar") <11> possible_keys = cipheycore.caesar_crack( <12> analysis, self.expected, self.group, self.p_value <13> ) <14> <15> n_candidates = len(possible_keys) <16> logger.debug(f"ROT47 returned {n_candidates} candidates") <17> <18> if n_candidates == 0: <19> logger.trace(f"Filtering for better results") <20> analysis = cipheycore.analyse_string(ctext, self.group) <21> possible_keys = cipheycore.caesar_crack( <22> analysis, self.expected, self.group, self.p_value <23> ) <24> <25> candidates = [] <26> <27> for candidate in possible_keys: <28> logger.trace(f"Candidate {candidate.key} has prob {candidate.p_value}") <29> translated = cipheycore.caesar_decrypt(ctext, candidate.key, self.group) <30> candidates.append(CrackResult(value=translated, key_info=candidate.key)) <31> <32> return candidates <33>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.rot47.Rot47.__init__ 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.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')
ciphey.basemods.Decoders.uuencode/Uuencode.decode
Modified
Ciphey~Ciphey
0ccd6cbf7b34e19dd0e57bb71a1def99e20f55e3
Clean up some things
<1>:<add> UUEncode (Unix to Unix Encoding) is a symmetric encryption <del> UUEncode (for Unix to Unix Encoding) is a symmetric encryption <4>:<add> This function decodes the input string 'ctext' if it has been encoded using 'uuencoder' <del> This function decodes the input string 'ctext' if it has been decoded using `uuencoder`. <5>:<add> It will return None otherwise <del> Will return 'None' otherwise <7>:<add> logger.trace("Attempting UUencode") <del> logger.trace("Attempting uuencode decode") <8>:<add> result = "" <9>:<add> # UUencoded messages may begin with prefix "begin" and end with suffix "end" <del> # uuencoded messages may begin with prefix "begin" and end with suffix "end". <10>:<add> # In that case, we use the codecs module in Python <del> # codecs module in python is used in that case <13>:<add> result = decode(bytes(ctext, "utf-8"), "uu").decode() <del> res = decode(bytes(ctext, "utf-8"), "uu").decode() <15>:<add> # If there isn't a "being" prefix and "end" suffix, we use the binascii module instead <del> # If there is no "begin" prefix & "end" suffix use binascii module. <16>:<add> # It is possible that the ctext has multiple lines, so convert each line and append <del> # It is possible that encoded string has multiple lines, so convert each line and append <17>:<add> ctext_split = list(filter(None, ctext.splitlines())) <del> ctext_split=list(filter(None, ctext.splitlines())) <18>:<del> res = "" <20>:<add> result += a2b_uu(ctext_split[i]).decode("utf-8") <del> res += a2b_uu(ctext_split[i]).decode("utf-8") <21>:<add> logger.
# module: ciphey.basemods.Decoders.uuencode @registry.register class Uuencode(Decoder[str, str]): + def decode(self, ctext: T) -> Optional[U]: - def decode(self, ctext: str) -> Optional[str]: <0> """ <1> UUEncode (for Unix to Unix Encoding) is a symmetric encryption <2> based on conversion of binary data (split into 6-bit blocks) into ASCII characters. <3> <4> This function decodes the input string 'ctext' if it has been decoded using `uuencoder`. <5> Will return 'None' otherwise <6> """ <7> logger.trace("Attempting uuencode decode") <8> try: <9> # uuencoded messages may begin with prefix "begin" and end with suffix "end". <10> # codecs module in python is used in that case <11> ctext_strip = ctext.strip() <12> if ctext_strip.startswith("begin") and ctext_strip.endswith("end"): <13> res = decode(bytes(ctext, "utf-8"), "uu").decode() <14> else: <15> # If there is no "begin" prefix & "end" suffix use binascii module. <16> # It is possible that encoded string has multiple lines, so convert each line and append <17> ctext_split=list(filter(None, ctext.splitlines())) <18> res = "" <19> for i in range(0, len(ctext_split)): <20> res += a2b_uu(ctext_split[i]).decode("utf-8") <21> logger.debug(f"uuencode decode gave '{res}'") <22> return res <23> except ValueError: <24> logger.trace("uuuencode decode failed") <25> return None <26>
ciphey.basemods.Decoders.uuencode/Uuencode.getParams
Modified
Ciphey~Ciphey
0ccd6cbf7b34e19dd0e57bb71a1def99e20f55e3
Clean up some things
<0>:<del> """No parameters needed""" <1>:<del> pass <2>:<add> return None
# module: ciphey.basemods.Decoders.uuencode @registry.register class Uuencode(Decoder[str, str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> """No parameters needed""" <1> pass <2>
===========changed ref 0=========== # module: ciphey.basemods.Decoders.uuencode @registry.register class Uuencode(Decoder[str, str]): + def decode(self, ctext: T) -> Optional[U]: - def decode(self, ctext: str) -> Optional[str]: """ + UUEncode (Unix to Unix Encoding) is a symmetric encryption - UUEncode (for Unix to Unix Encoding) is a symmetric encryption based on conversion of binary data (split into 6-bit blocks) into ASCII characters. + This function decodes the input string 'ctext' if it has been encoded using 'uuencoder' - This function decodes the input string 'ctext' if it has been decoded using `uuencoder`. + It will return None otherwise - Will return 'None' otherwise """ + logger.trace("Attempting UUencode") - logger.trace("Attempting uuencode decode") + result = "" try: + # UUencoded messages may begin with prefix "begin" and end with suffix "end" - # uuencoded messages may begin with prefix "begin" and end with suffix "end". + # In that case, we use the codecs module in Python - # codecs module in python is used in that case ctext_strip = ctext.strip() if ctext_strip.startswith("begin") and ctext_strip.endswith("end"): + result = decode(bytes(ctext, "utf-8"), "uu").decode() - res = decode(bytes(ctext, "utf-8"), "uu").decode() else: + # If there isn't a "being" prefix and "end" suffix, we use the binascii module instead - # If there is no "begin" prefix & "end" suffix use binascii module. + # It is possible that the ctext has multiple lines, so convert each line and append - # It is possible that encoded string has multiple lines, so convert each line and append + ctext_split = list(filter(None, ctext.splitlines())) - ctext_split=list(filter(</s> ===========changed ref 1=========== # module: ciphey.basemods.Decoders.uuencode @registry.register class Uuencode(Decoder[str, str]): + def decode(self, ctext: T) -> Optional[U]: - def decode(self, ctext: str) -> Optional[str]: # offset: 1 <s> ctext_split = list(filter(None, ctext.splitlines())) - ctext_split=list(filter(None, ctext.splitlines())) - res = "" for i in range(0, len(ctext_split)): + result += a2b_uu(ctext_split[i]).decode("utf-8") - res += a2b_uu(ctext_split[i]).decode("utf-8") + logger.debug(f"UUencode successful, returning '{result}'") - logger.debug(f"uuencode decode gave '{res}'") + return result - return res + except Exception: - except ValueError: + logger.trace("Failed to decode UUencode") - logger.trace("uuuencode decode failed") return None
ciphey.basemods.Crackers.soundex/Soundex.attemptCrack
Modified
Ciphey~Ciphey
7da61dbe68e55e24efeac56238ffde09ee929d65
Fix Soundex
<27>:<add> soundex_keys = self.SOUNDEX_DICT.keys() <30>:<add> if code in soundex_keys: <add> word_list.append(self.SOUNDEX_DICT[code]) <del> word_list.append(self.SOUNDEX_DICT[code])
# module: ciphey.basemods.Crackers.soundex @registry.register class Soundex(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> """ <1> Attempts to crack Soundex by generating all possible combinations. <2> """ <3> logger.trace("Attempting Soundex cracker") <4> word_list = [] <5> sentences = [] <6> result = [] <7> <8> # Convert to uppercase and replace delimiters and whitespace with nothing <9> ctext = re.sub(r"[,;:\-\s]", "", ctext.upper()) <10> <11> # Make sure ctext contains only A-Z and 0-9 <12> if bool(re.search(r"[^A-Z0-9]", ctext)) is True: <13> logger.trace("Failed to crack soundex due to non soundex character(s)") <14> return None <15> <16> # Make sure ctext is divisible by 4 <17> ctext_len = len(ctext) <18> if ctext_len % 4: <19> logger.trace( <20> f"Failed to decode Soundex because length must be a multiple of 4, not '{ctext_len}'" <21> ) <22> return None <23> <24> # Split ctext into groups of 4 <25> ctext = " ".join(ctext[i : i + 4] for i in range(0, len(ctext), 4)) <26> ctext_split = ctext.split(" ") <27> <28> # Find all words that correspond to each given soundex code <29> for code in ctext_split: <30> word_list.append(self.SOUNDEX_DICT[code]) <31> <32> logger.debug(f"Possible words for given encoded text: {word_list}") <33> <34> # Find all possible sentences <35> self.getSentenceCombo( <36> word_list, <37> sentences, <38> self.frequency_dict, <39> self.sentence_freq, <40> self.word_freq, <41> ) </s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.soundex @registry.register class Soundex(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 sorted_sentences = self.sortlistwithdict(sentences, self.frequency_dict) for sentence in sorted_sentences: result.append(CrackResult(value=sentence)) logger.trace(f"Soundex cracker - Returning results: {result}") return result ===========unchanged ref 0=========== at: ciphey.basemods.Crackers.soundex.Soundex sortlistwithdict(listtosort, hashes) getSentenceCombo(A, sentences, frequency_dict, sentence_freq, word_freq, result="", n=0) at: ciphey.basemods.Crackers.soundex.Soundex.__init__ self.SOUNDEX_DICT = config.get_resource(self._params()["dict"], Translation) self.word_freq = config.get_resource(self._params()["freq"], Translation) self.frequency_dict = {} self.sentence_freq = 0 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: re search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] search(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr at: typing List = _alias(list, 1, inst=False, name='List')
tests.test_main/test_galactic_Xproblem
Modified
Ciphey~Ciphey
93322cfdc0836292bfe6f716ec123f14adf81a27
Fix issue #262 - 'x' surrounded by letters in Galactic Alphabet Decoder
<2>:<add> "⍑ᔑꖎ╎⎓ᔑ ̇/, ̇/||ꖎ𝙹!¡⍑𝙹リᒷ, ᔑ ̇/ ᔑꖎ𝙹リᒷ ᔑリ↸ ̇/ᒷ∷𝙹 ̇/ ⎓∷𝙹ᒲ 𝙹 ̇/⎓𝙹∷↸" <del> "𝙹 ̇/⎓𝙹∷↸ ℸ ̣ ⍑ᒷ ̇/ ╎ᓭ ╎リ ℸ ̣ ⍑ᒷ ᒲ╎↸↸ꖎᒷ ℸ ̣ ⍑ᔑℸ ̣ ᓭ ∴⍑|| ╎ℸ ̣ ⎓ᔑ╎ꖎᓭ", <4>:<add> assert res.lower() == "halifax, xylophone, a x alone and xerox from oxford" <del> assert res.lower() == "oxford the x is in the middle thats why it fails"
# module: tests.test_main - @pytest.mark.skip(reason="https://github.com/Ciphey/Ciphey/issues/262") def test_galactic_Xproblem(): <0> res = decrypt( <1> Config().library_default().complete_config(), <2> "𝙹 ̇/⎓𝙹∷↸ ℸ ̣ ⍑ᒷ ̇/ ╎ᓭ ╎リ ℸ ̣ ⍑ᒷ ᒲ╎↸↸ꖎᒷ ℸ ̣ ⍑ᔑℸ ̣ ᓭ ∴⍑|| ╎ℸ ̣ ⎓ᔑ╎ꖎᓭ", <3> ) <4> assert res.lower() == "oxford the x is in the middle thats why it fails" <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()
ciphey.basemods.Decoders.galactic/Galactic.decode
Modified
Ciphey~Ciphey
93322cfdc0836292bfe6f716ec123f14adf81a27
Fix issue #262 - 'x' surrounded by letters in Galactic Alphabet Decoder
<24>:<add> # Take out the problematic characters consisting of multiple symbols <29>:<add> .replace("̇", "x") <del> .replace(" ̇", " x") <32>:<add> <del> # Take out the problematic characters consisting of multiple symbols
# 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> logger.trace("Attempting Standard Galactic Alphabet Decoder") <5> <6> # To avoid complications, only move forward with the decoding if we can <7> # reasonably assume that the input string is written in the galactic alphabet <8> galactic_matches = 0 <9> for symbol in self.GALACTIC_DICT.keys(): <10> # These symbols are assumed to be frequent enough in regular <11> # text to be skipped when counting the matches. All others are counted. <12> if symbol in ctext and symbol not in ["!", "|"]: <13> galactic_matches += 1 <14> else: <15> continue <16> if galactic_matches == 0: <17> logger.trace( <18> "No matching galactic alphabet letters found. Skipping galactic decoder..." <19> ) <20> return None <21> logger.trace(f"{galactic_matches} galactic alphabet letters found. ") <22> <23> result = "" <24> ctext = ( <25> ctext.replace("||", "|") <26> .replace("/", "") <27> .replace("¡", "") <28> .replace(" ̣ ", "") <29> .replace(" ̇", " x") <30> ) <31> logger.trace(f"Modified string is {ctext}") <32> # Take out the problematic characters consisting of multiple symbols <33> for letter in ctext: <34> if letter in self.GALACTIC_DICT.keys(): <35> # Match every letter of the input to its galactic counterpoint <36> result += self.GALACTIC_DICT[letter] <37> else: <38> # If the current character is not in the defined alphabet, <39> # just accept it as-</s>
===========below chunk 0=========== # module: ciphey.basemods.Decoders.galactic @registry.register class Galactic(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: # offset: 1 result += letter result = result.replace("x ", "x") # Remove the trailing space (appearing as a leading space) # from the x that results from the diacritic replacement logger.trace(f"Decoded string is {result}") return result ===========unchanged ref 0=========== at: ciphey.basemods.Decoders.galactic.Galactic.__init__ self.GALACTIC_DICT = config.get_resource(self._params()["dict"], Translation) at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] ===========changed ref 0=========== # module: tests.test_main - @pytest.mark.skip(reason="https://github.com/Ciphey/Ciphey/issues/262") def test_galactic_Xproblem(): res = decrypt( Config().library_default().complete_config(), + "⍑ᔑꖎ╎⎓ᔑ ̇/, ̇/||ꖎ𝙹!¡⍑𝙹リᒷ, ᔑ ̇/ ᔑꖎ𝙹リᒷ ᔑリ↸ ̇/ᒷ∷𝙹 ̇/ ⎓∷𝙹ᒲ 𝙹 ̇/⎓𝙹∷↸" - "𝙹 ̇/⎓𝙹∷↸ ℸ ̣ ⍑ᒷ ̇/ ╎ᓭ ╎リ ℸ ̣ ⍑ᒷ ᒲ╎↸↸ꖎᒷ ℸ ̣ ⍑ᔑℸ ̣ ᓭ ∴⍑|| ╎ℸ ̣ ⎓ᔑ╎ꖎᓭ", ) + assert res.lower() == "halifax, xylophone, a x alone and xerox from oxford" - assert res.lower() == "oxford the x is in the middle thats why it fails"
ciphey.ciphey/main
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<1>:<add> <del> <2>:<add> Documentation: <del> Documentation: <6>:<add> GitHub: <del> GitHub: <12>:<add> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <del> Basic Usage: ciphey -t "aGVsbG8gbXkgbmFtZSBpcyBiZWU=" <13>:<add> <del> <24>:<del>
<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, 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://github.com/Ciphey/Ciphey/wiki\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("C</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.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["</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.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.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"] is not None: config.update_format("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() 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.</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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 3 <s> red]") @click.pass_context def all_procedure(ctx): print_help(ctx) all_procedure() return None if issubclass(config.objs["format"], type(kwargs["text"])): pass elif config.objs["format"] == str and type(kwargs["text"]) is bytes: kwargs["text"] = kwargs["text"].decode("utf-8") elif config.objs["format"] == bytes and type(kwargs["text"]) is str: kwargs["text"] = kwargs["text"].encode("utf-8") else: raise TypeError(f"Cannot load type {config.format} from {type(kwargs['text'])}") 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: config.set_spinner(sp) result = decrypt(config, kwargs["text"]) if result is None: result = "Could not find any solutions." print(result)
ciphey.iface._registry/Registry._real_register
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<41>:<add> arg = [ <add> get_args(i) <add> for i in input_type.__orig_bases__ <add> if get_origin(i) == Checker <add> ][0] <del> arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] <43>:<add> raise TypeError("No argument for Checker") <del> raise TypeError(f"No argument for Checker")
# module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: <0> name = input_type.__name__.lower() <1> name_target = self._names[name] = (input_type, set()) <2> <3> if issubclass(input_type, Targeted): <4> target = input_type.getTarget() <5> else: <6> target = None <7> <8> if issubclass(input_type, Searcher): <9> module_type = module_base = Searcher <10> module_args = () <11> else: <12> module_type: Optional[Type] = None <13> module_base = None <14> <15> # Work out what module type this is <16> if len(args) == 0 and hasattr(input_type, "__orig_bases__"): <17> for i in input_type.__orig_bases__: <18> if module_type is not None: <19> raise TypeError( <20> f"Type derived from multiple registrable base classes {i} and {module_type}" <21> ) <22> module_base = get_origin(i) <23> if module_base not in self._modules: <24> continue <25> module_type = i <26> else: <27> for i in self._modules: <28> if not issubclass(input_type, i): <29> continue <30> if module_type is not None: <31> raise TypeError( <32> f"Type derived from multiple registrable base classes {i} and {module_type}" <33> ) <34> module_type = i <35> if module_type is None: <36> raise TypeError("No registrable base class") <37> <38> # Replace input type with polymorphic checker if required <39> if issubclass(input_type, Checker): <40> if len(args) == 0: <41> arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] <42> if len(arg) != 1: <43> raise TypeError(f"No argument for Checker") <44> input_type =</s>
===========below chunk 0=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 else: input_type = input_type.convert(set(args)) self._register_one(input_type, PolymorphicChecker, []) # Refresh the names with the new type name_target = self._names[name] = (input_type, {PolymorphicChecker}) # Now handle the difference between register and register_multi if len(args) == 0: if module_type is PolymorphicChecker: module_base = PolymorphicChecker elif 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: # 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() PolymorphicChecker(config: Config) Checker(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, PolymorphicChecker} _register_one(input_type, module_base, module_args) _real_register(input_type: type, *args) -> Type at: ciphey.iface._registry.Registry._real_register name = input_type.__name__.lower() target = None target = input_type.getTarget() at: typing get_origin(tp: Any) -> Optional[Any] get_args(tp: Any) -> Tuple[Any, ...] ===========changed ref 0=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 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, 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): """Ciphey - Automated Decryption Tool + - + Documentation: - Documentation: https://github.com/Ciphey/Ciphey/wiki\n Discord (support here, we're online most of the day): https://discord.ciphey.online/\n + GitHub: - 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=" - 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 "</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.option("-f", "--file", type=click.File("rb"), required=False) @click.argument("text_stdin", callback=get_name, required=False) def main(**kwargs): # offset: 1 <s> 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.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 </s>
ciphey.iface._config/Cache.mark_ctext
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: <del> if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4:
# 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.__repr__()} too short!") <2> return False <3> <4> if ctext in self._cache: <5> logger.trace(f"Deduped {ctext.__repr__()}") <6> return False <7> <8> logger.trace(f"New ctext {ctext.__repr__()}") <9> <10> self._cache[ctext] = {} <11> return True <12>
===========unchanged ref 0=========== at: ciphey.iface._config.Cache.__init__ self._cache: Dict[Any, Dict[str, Any]] = {} ===========changed ref 0=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========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()) 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 and hasattr(input_type, "__orig_bases__"): 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") # Replace input type with polymorphic checker if required if issubclass(input_type, Checker): if len(args) == 0: + arg = [ + get_args(i) + for i in input_type.__orig_bases__ + if get_origin(i) == Checker + ][0] - arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - </s> ===========changed ref 2=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 <s>) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - raise TypeError(f"No argument for Checker") input_type = input_type.convert({arg[0]}) else: input_type = input_type.convert(set(args)) self._register_one(input_type, PolymorphicChecker, []) # Refresh the names with the new type name_target = self._names[name] = (input_type, {PolymorphicChecker}) # Now handle the difference between register and register_multi if len(args) == 0: if module_type is PolymorphicChecker: module_base = PolymorphicChecker elif 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: # 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 ===========changed ref 3=========== <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, 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): """Ciphey - Automated Decryption Tool + - + Documentation: - Documentation: https://github.com/Ciphey/Ciphey/wiki\n Discord (support here, we're online most of the day): https://discord.ciphey.online/\n + GitHub: - 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=" - 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 "</s>
ciphey.iface._config/Config.update_log_level
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<16>:<add> import sys <add> <17>:<del> import sys
# module: ciphey.iface._config class Config: def update_log_level(self, verbosity: Optional[int]): <0> if verbosity is None: <1> return <2> self.verbosity = verbosity <3> quiet_list = [ <4> "ERROR", <5> "CRITICAL", <6> ] <7> loud_list = ["DEBUG", "TRACE"] <8> verbosity_name: str <9> if verbosity == 0: <10> verbosity_name = "WARNING" <11> elif verbosity >= 0: <12> verbosity_name = loud_list[min(len(loud_list), verbosity) - 1] <13> else: <14> verbosity_name = quiet_list[min(len(quiet_list), -verbosity) - 1] <15> <16> from loguru import logger <17> import sys <18> <19> logger.remove() <20> if self.verbosity is None: <21> return <22> logger.configure() <23> if self.verbosity > 0: <24> logger.add( <25> sink=sys.stderr, level=verbosity_name, colorize=sys.stderr.isatty() <26> ) <27> logger.opt(colors=True) <28> else: <29> logger.add( <30> sink=sys.stderr, <31> level=verbosity_name, <32> colorize=False, <33> format="{message}", <34> ) <35> logger.debug(f"Verbosity set to level {verbosity} ({verbosity_name})") <36>
===========unchanged ref 0=========== at: ciphey.iface._config.Config.__init__ self.verbosity: int = 0 at: sys stderr: TextIO at: typing.IO __slots__ = () isatty() -> bool ===========changed ref 0=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 1=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 2=========== # 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()) 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 and hasattr(input_type, "__orig_bases__"): 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") # Replace input type with polymorphic checker if required if issubclass(input_type, Checker): if len(args) == 0: + arg = [ + get_args(i) + for i in input_type.__orig_bases__ + if get_origin(i) == Checker + ][0] - arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - </s> ===========changed ref 3=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 <s>) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - raise TypeError(f"No argument for Checker") input_type = input_type.convert({arg[0]}) else: input_type = input_type.convert(set(args)) self._register_one(input_type, PolymorphicChecker, []) # Refresh the names with the new type name_target = self._names[name] = (input_type, {PolymorphicChecker}) # Now handle the difference between register and register_multi if len(args) == 0: if module_type is PolymorphicChecker: module_base = PolymorphicChecker elif 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: # 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 ===========changed ref 4=========== <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, 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): """Ciphey - Automated Decryption Tool + - + Documentation: - Documentation: https://github.com/Ciphey/Ciphey/wiki\n Discord (support here, we're online most of the day): https://discord.ciphey.online/\n + GitHub: - 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=" - 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 "</s>
ciphey.basemods.Decoders.base69/Base69.decode
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<26>:<add> except Exception: <del> except:
# module: ciphey.basemods.Decoders.base69 @registry.register + class Base69(Decoder[str]): - class Base69(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: <0> """ <1> Performs Base69 decoding <2> """ <3> # Remove whitespace <4> try: <5> ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) <6> extra_bytes = 0 <7> clen = len(ctext) <8> <9> if ctext[:-1] == "=": <10> extra_bytes = int(ctext[clen - 2]) <11> <12> CHUNK_COUNT = ceil(clen / 16) <13> result = [0 for _ in range(CHUNK_COUNT * 7 - extra_bytes)] <14> <15> for i in range(CHUNK_COUNT): <16> chunk_string = ctext[i * 16 : (i + 1) * 16] <17> if extra_bytes and (i == CHUNK_COUNT - 1): <18> insert = self.decode_chunk(chunk_string) <19> for n, elem in enumerate(insert[0 : 7 - extra_bytes]): <20> result[n + i * 7] = elem <21> else: <22> insert = self.decode_chunk(chunk_string) <23> for n, elem in enumerate(insert): <24> result[n + i * 7] = elem % 256 <25> return bytearray(result).decode().strip("\x00") <26> except: <27> return None <28>
===========unchanged ref 0=========== at: math ceil(x: SupportsFloat, /) -> int at: re UNICODE = RegexFlag.UNICODE sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int=..., flags: _FlagsType=...) -> AnyStr ===========changed ref 0=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 1=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 2=========== # module: ciphey.iface._config class Config: def update_log_level(self, verbosity: Optional[int]): if verbosity is None: return self.verbosity = verbosity quiet_list = [ "ERROR", "CRITICAL", ] loud_list = ["DEBUG", "TRACE"] verbosity_name: str if verbosity == 0: verbosity_name = "WARNING" elif verbosity >= 0: verbosity_name = loud_list[min(len(loud_list), verbosity) - 1] else: verbosity_name = quiet_list[min(len(quiet_list), -verbosity) - 1] + import sys + from loguru import logger - import sys logger.remove() if self.verbosity is None: return logger.configure() if self.verbosity > 0: logger.add( sink=sys.stderr, level=verbosity_name, colorize=sys.stderr.isatty() ) logger.opt(colors=True) else: logger.add( sink=sys.stderr, level=verbosity_name, colorize=False, format="{message}", ) logger.debug(f"Verbosity set to level {verbosity} ({verbosity_name})") ===========changed ref 3=========== # 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()) 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 and hasattr(input_type, "__orig_bases__"): 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") # Replace input type with polymorphic checker if required if issubclass(input_type, Checker): if len(args) == 0: + arg = [ + get_args(i) + for i in input_type.__orig_bases__ + if get_origin(i) == Checker + ][0] - arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - </s> ===========changed ref 4=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 <s>) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - raise TypeError(f"No argument for Checker") input_type = input_type.convert({arg[0]}) else: input_type = input_type.convert(set(args)) self._register_one(input_type, PolymorphicChecker, []) # Refresh the names with the new type name_target = self._names[name] = (input_type, {PolymorphicChecker}) # Now handle the difference between register and register_multi if len(args) == 0: if module_type is PolymorphicChecker: module_base = PolymorphicChecker elif 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: # 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.Crackers.xor_single/XorSingle.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<1>:<add> "expected": ParamSpec( <del> "expected": ciphey.iface.ParamSpec( <6>:<add> "p_value": ParamSpec( <del> "p_value": ciphey.iface.ParamSpec(
# module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @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> "p_value": ciphey.iface.ParamSpec( <7> desc="The p-value to use for standard frequency analysis", <8> req=False, <9> default=0.01, <10> ) <11> # TODO: add "filter" param <12> } <13>
===========unchanged ref 0=========== at: ciphey.iface._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) ===========changed ref 0=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 1=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 2=========== # module: ciphey.basemods.Decoders.base69 @registry.register + class Base69(Decoder[str]): - class Base69(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: """ Performs Base69 decoding """ # Remove whitespace try: ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) extra_bytes = 0 clen = len(ctext) if ctext[:-1] == "=": extra_bytes = int(ctext[clen - 2]) CHUNK_COUNT = ceil(clen / 16) result = [0 for _ in range(CHUNK_COUNT * 7 - extra_bytes)] for i in range(CHUNK_COUNT): chunk_string = ctext[i * 16 : (i + 1) * 16] if extra_bytes and (i == CHUNK_COUNT - 1): insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert[0 : 7 - extra_bytes]): result[n + i * 7] = elem else: insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert): result[n + i * 7] = elem % 256 return bytearray(result).decode().strip("\x00") + except Exception: - except: return None ===========changed ref 3=========== # module: ciphey.iface._config class Config: def update_log_level(self, verbosity: Optional[int]): if verbosity is None: return self.verbosity = verbosity quiet_list = [ "ERROR", "CRITICAL", ] loud_list = ["DEBUG", "TRACE"] verbosity_name: str if verbosity == 0: verbosity_name = "WARNING" elif verbosity >= 0: verbosity_name = loud_list[min(len(loud_list), verbosity) - 1] else: verbosity_name = quiet_list[min(len(quiet_list), -verbosity) - 1] + import sys + from loguru import logger - import sys logger.remove() if self.verbosity is None: return logger.configure() if self.verbosity > 0: logger.add( sink=sys.stderr, level=verbosity_name, colorize=sys.stderr.isatty() ) logger.opt(colors=True) else: logger.add( sink=sys.stderr, level=verbosity_name, colorize=False, format="{message}", ) logger.debug(f"Verbosity set to level {verbosity} ({verbosity_name})") ===========changed ref 4=========== # 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()) 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 and hasattr(input_type, "__orig_bases__"): 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") # Replace input type with polymorphic checker if required if issubclass(input_type, Checker): if len(args) == 0: + arg = [ + get_args(i) + for i in input_type.__orig_bases__ + if get_origin(i) == Checker + ][0] - arg = [get_args(i) for i in input_type.__orig_bases__ if get_origin(i) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - </s> ===========changed ref 5=========== # module: ciphey.iface._registry class Registry: def _real_register(self, input_type: type, *args) -> Type: # offset: 1 <s>) == Checker][0] if len(arg) != 1: + raise TypeError("No argument for Checker") - raise TypeError(f"No argument for Checker") input_type = input_type.convert({arg[0]}) else: input_type = input_type.convert(set(args)) self._register_one(input_type, PolymorphicChecker, []) # Refresh the names with the new type name_target = self._names[name] = (input_type, {PolymorphicChecker}) # Now handle the difference between register and register_multi if len(args) == 0: if module_type is PolymorphicChecker: module_base = PolymorphicChecker elif 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: # 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.Searchers.astar/Graph.a_star_algorithm
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<26>:<add> if n is None or g[v] + self.h(v) < g[n] + self.h(n): <del> if n == None or g[v] + self.h(v) < g[n] + self.h(n): <30>:<add> if n is None: <del> if n == None: <37>:<add> # TODO Make it exit if decrypter returns True <del> # TODO Make it exit if decryptor returns True
# module: ciphey.basemods.Searchers.astar class Graph: def a_star_algorithm(self, start_node: Node, stop_node: Node): <0> # TODO store the graph as an attribute <1> # open_list is a list of nodes which have been visited, but who's neighbors <2> # haven't all been inspected, starts off with the start node <3> # closed_list is a list of nodes which have been visited <4> # and who's neighbors have been inspected <5> open_list = set([start_node]) <6> closed_list = set([]) <7> <8> # g contains current distances from start_node to all other nodes <9> # the default value (if it's not found in the map) is +infinity <10> g = {} <11> <12> g[start_node] = 0 <13> <14> # parents contains an adjacency map of all nodes <15> parents = {} <16> parents[start_node] = start_node <17> <18> while len(open_list) > 0: <19> print(f"The open list is {open_list}") <20> n = None <21> <22> # find a node with the lowest value of f() - evaluation function <23> for v in open_list: <24> # TODO if v == decoder, run the decoder <25> print(f"The for loop node v is {v}") <26> if n == None or g[v] + self.h(v) < g[n] + self.h(n): <27> n = v <28> print(f"The value of n is {n}") <29> <30> if n == None: <31> print("Path does not exist!") <32> return None <33> <34> # if the current node is the stop_node <35> # then we begin reconstructin the path from it to the start_node <36> # NOTE Uncomment this for an exit condition <37> # TODO Make it exit if decryptor returns True <38> # TODO We need to append the decryption methods to each node <39> # So when we reconstruct the path we can reconstruct the decryptions <40> # used <41> if n == stop</s>
===========below chunk 0=========== # module: ciphey.basemods.Searchers.astar class Graph: def a_star_algorithm(self, start_node: Node, stop_node: Node): # offset: 1 print("n is the stop node, we are stopping!") reconst_path = [] while parents[n] != n: reconst_path.append(n) n = parents[n] reconst_path.append(start_node) reconst_path.reverse() print("Path found: {}".format(reconst_path)) return reconst_path print(n) for (m, weight) in self.get_neighbors(n): print(f"And the iteration is ({m}, {weight})") # if the current node isn't in both open_list and closed_list # add it to open_list and note n as it's parent if m not in open_list and m not in closed_list: open_list.add(m) parents[m] = n g[m] = g[n] + weight # otherwise, check if it's quicker to first visit n, then m # and if it is, update parent data and g data # and if the node was in the closed_list, move it to open_list else: if g[m] > g[n] + weight: g[m] = g[n] + weight parents[m] = n if m in closed_list: closed_list.remove(m) open_list.add(m) # remove n from the open_list, and add it to closed_list # because all of his neighbors were inspected # open_list.remove(node) # closed_list.add(node) open_list.remove(n) closed_list.add(n) print("\n") print("Path does not exist!") return None ===========unchanged ref 0=========== at: ciphey.basemods.Searchers.astar Node(config, h: float=None, edges: (any, float)=None, ctext: str=None) at: ciphey.basemods.Searchers.astar.Graph get_neighbors(v) at: ciphey.basemods.Searchers.astar.Graph.__init__ self.original_input = cipheycore.info_content(input) ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 2=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 4=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 5=========== # module: ciphey.basemods.Decoders.base69 @registry.register + class Base69(Decoder[str]): - class Base69(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: """ Performs Base69 decoding """ # Remove whitespace try: ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) extra_bytes = 0 clen = len(ctext) if ctext[:-1] == "=": extra_bytes = int(ctext[clen - 2]) CHUNK_COUNT = ceil(clen / 16) result = [0 for _ in range(CHUNK_COUNT * 7 - extra_bytes)] for i in range(CHUNK_COUNT): chunk_string = ctext[i * 16 : (i + 1) * 16] if extra_bytes and (i == CHUNK_COUNT - 1): insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert[0 : 7 - extra_bytes]): result[n + i * 7] = elem else: insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert): result[n + i * 7] = elem % 256 return bytearray(result).decode().strip("\x00") + except Exception: - except: return None ===========changed ref 6=========== # module: ciphey.iface._config class Config: def update_log_level(self, verbosity: Optional[int]): if verbosity is None: return self.verbosity = verbosity quiet_list = [ "ERROR", "CRITICAL", ] loud_list = ["DEBUG", "TRACE"] verbosity_name: str if verbosity == 0: verbosity_name = "WARNING" elif verbosity >= 0: verbosity_name = loud_list[min(len(loud_list), verbosity) - 1] else: verbosity_name = quiet_list[min(len(quiet_list), -verbosity) - 1] + import sys + from loguru import logger - import sys logger.remove() if self.verbosity is None: return logger.configure() if self.verbosity > 0: logger.add( sink=sys.stderr, level=verbosity_name, colorize=sys.stderr.isatty() ) logger.opt(colors=True) else: logger.add( sink=sys.stderr, level=verbosity_name, colorize=False, format="{message}", ) logger.debug(f"Verbosity set to level {verbosity} ({verbosity_name})")
ciphey.basemods.Checkers.gtest/GTestChecker.check
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> logger.trace("Trying entropy checker") <del> logger.trace(f"Trying entropy checker")
# module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: <0> logger.trace(f"Trying entropy checker") <1> pass <2>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") at: ciphey.iface._modules.Checker getExpectedRuntime(self, text: T) -> float ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 2=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 4=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 5=========== # module: ciphey.basemods.Searchers.astar adjacency_list = { "A": [("B", 1), ("C", 3), ("D", 7)], "B": [("D", 5)], "C": [("D", 12)], } A = Node(1) B = Node(7) C = Node(9) D = Node(16) A.edges = [(B, 1), (C, 3), (D, 7)] B.edges = [(D, 5)] C.edges = [(D, 12)] # TODO use a dictionary comprehension to make this adjacency_list = { A: A.edges, B: B.edges, C: C.edges, } graph1 = Graph(adjacency_list) graph1.a_star_algorithm(A, D) """ + Maybe after it - Maybe after it """ ===========changed ref 6=========== # module: ciphey.basemods.Decoders.base69 @registry.register + class Base69(Decoder[str]): - class Base69(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: """ Performs Base69 decoding """ # Remove whitespace try: ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) extra_bytes = 0 clen = len(ctext) if ctext[:-1] == "=": extra_bytes = int(ctext[clen - 2]) CHUNK_COUNT = ceil(clen / 16) result = [0 for _ in range(CHUNK_COUNT * 7 - extra_bytes)] for i in range(CHUNK_COUNT): chunk_string = ctext[i * 16 : (i + 1) * 16] if extra_bytes and (i == CHUNK_COUNT - 1): insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert[0 : 7 - extra_bytes]): result[n + i * 7] = elem else: insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert): result[n + i * 7] = elem % 256 return bytearray(result).decode().strip("\x00") + except Exception: - except: return None ===========changed ref 7=========== # module: ciphey.iface._config class Config: def update_log_level(self, verbosity: Optional[int]): if verbosity is None: return self.verbosity = verbosity quiet_list = [ "ERROR", "CRITICAL", ] loud_list = ["DEBUG", "TRACE"] verbosity_name: str if verbosity == 0: verbosity_name = "WARNING" elif verbosity >= 0: verbosity_name = loud_list[min(len(loud_list), verbosity) - 1] else: verbosity_name = quiet_list[min(len(quiet_list), -verbosity) - 1] + import sys + from loguru import logger - import sys logger.remove() if self.verbosity is None: return logger.configure() if self.verbosity > 0: logger.add( sink=sys.stderr, level=verbosity_name, colorize=sys.stderr.isatty() ) logger.opt(colors=True) else: logger.add( sink=sys.stderr, level=verbosity_name, colorize=False, format="{message}", ) logger.debug(f"Verbosity set to level {verbosity} ({verbosity_name})")
tests.integration/testIntegration.test_integration_charlesBabbage
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<3>:<add> """ <del> """
# module: tests.integration class testIntegration(unittest.TestCase): def test_integration_charlesBabbage(self): <0> """ <1> I had a bug with this exact string <2> Bug is that chi squared does not score this as True <3> """ <4> text = """Charles Babbage, FRS (26 December 1791 - 18 October 1871) was an English mathematician, philosopher, inventor and mechanical engineer who originated the concept of a programmable computer. Considered a "father of the computer", Babbage is credited with inventing the first mechanical computer that eventually led to more complex designs. Parts of his uncompleted mechanisms are on display in the London Science Museum. In 1991, a perfectly functioning difference engine was constructed from Babbage's original plans. Built to tolerances achievable in the 19th century, the success of the finished engine indicated that Babbage's machine would have worked. Nine years later, the Science Museum completed the printer Babbage had designed for the difference engine.""" <5> lc = LanguageChecker.Checker() <6> result = lc.check(text) <7> self.assertEqual(result, True) <8>
===========unchanged ref 0=========== at: tests.integration.testIntegration.test_integration_addition temp3 = temp + temp2 lc3 = lc + lc2 at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertAlmostEqual(first: float, second: float, places: Optional[int]=..., msg: Any=..., delta: Optional[float]=...) -> None assertAlmostEqual(first: datetime.datetime, second: datetime.datetime, places: Optional[int]=..., msg: Any=..., delta: Optional[datetime.timedelta]=...) -> None ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 2=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 3=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 4=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 5=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 6=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 7=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 8=========== # module: ciphey.basemods.Searchers.astar adjacency_list = { "A": [("B", 1), ("C", 3), ("D", 7)], "B": [("D", 5)], "C": [("D", 12)], } A = Node(1) B = Node(7) C = Node(9) D = Node(16) A.edges = [(B, 1), (C, 3), (D, 7)] B.edges = [(D, 5)] C.edges = [(D, 12)] # TODO use a dictionary comprehension to make this adjacency_list = { A: A.edges, B: B.edges, C: C.edges, } graph1 = Graph(adjacency_list) graph1.a_star_algorithm(A, D) """ + Maybe after it - Maybe after it """ ===========changed ref 9=========== # module: ciphey.basemods.Decoders.base69 @registry.register + class Base69(Decoder[str]): - class Base69(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: """ Performs Base69 decoding """ # Remove whitespace try: ctext = re.sub(r"\s+", "", ctext, flags=re.UNICODE) extra_bytes = 0 clen = len(ctext) if ctext[:-1] == "=": extra_bytes = int(ctext[clen - 2]) CHUNK_COUNT = ceil(clen / 16) result = [0 for _ in range(CHUNK_COUNT * 7 - extra_bytes)] for i in range(CHUNK_COUNT): chunk_string = ctext[i * 16 : (i + 1) * 16] if extra_bytes and (i == CHUNK_COUNT - 1): insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert[0 : 7 - extra_bytes]): result[n + i * 7] = elem else: insert = self.decode_chunk(chunk_string) for n, elem in enumerate(insert): result[n + i * 7] = elem % 256 return bytearray(result).decode().strip("\x00") + except Exception: - except: return None
ciphey.basemods.Crackers.affine/Affine.attemptCrack
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<9>:<add> for a in range(1, self.alphabet_length) <del> for a in range(1, self.ALPHABET_LENGTH) <10>:<add> if mathsHelper.gcd(a, self.alphabet_length) == 1 <del> if mathsHelper.gcd(a, self.ALPHABET_LENGTH) == 1 <13>:<add> f"Trying Affine Cracker with {len(possible_a)} a-values and {self.alphabet_length} b-values" <del> f"Trying Affine Cracker with {len(possible_a)} a-values and {self.ALPHABET_LENGTH} b-values" <17>:<add> a_inv = mathsHelper.mod_inv(a, self.alphabet_length) <del> a_inv = mathsHelper.mod_inv(a, self.ALPHABET_LENGTH) <21>:<add> for b in range(self.alphabet_length): <del> for b in range(self.ALPHABET_LENGTH): <23>:<add> translated = self.decrypt(ctext.lower(), a_inv, b, self.alphabet_length) <del> translated = self.decrypt(ctext.lower(), a_inv, b, self.ALPHABET_LENGTH) <26>:<add> if candidate_probability > self.plaintext_prob_threshold: <del> if candidate_probability > self.PLAINTEXT_PROB_THRESHOLD:
# module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> """ <1> Brute forces all the possible combinations of a and b to attempt to crack the cipher. <2> """ <3> logger.trace("Attempting affine") <4> candidates = [] <5> <6> # a and b are coprime if gcd(a,b) is 1. <7> possible_a = [ <8> a <9> for a in range(1, self.ALPHABET_LENGTH) <10> if mathsHelper.gcd(a, self.ALPHABET_LENGTH) == 1 <11> ] <12> logger.debug( <13> f"Trying Affine Cracker with {len(possible_a)} a-values and {self.ALPHABET_LENGTH} b-values" <14> ) <15> <16> for a in possible_a: <17> a_inv = mathsHelper.mod_inv(a, self.ALPHABET_LENGTH) <18> # If there is no inverse, we cannot decrypt the text <19> if a_inv is None: <20> continue <21> for b in range(self.ALPHABET_LENGTH): <22> # Pass in lowered text. This means that we expect alphabets to not contain both 'a' and 'A'. <23> translated = self.decrypt(ctext.lower(), a_inv, b, self.ALPHABET_LENGTH) <24> <25> candidate_probability = self.plaintext_probability(translated) <26> if candidate_probability > self.PLAINTEXT_PROB_THRESHOLD: <27> candidates.append( <28> CrackResult( <29> value=fix_case(translated, ctext), key_info=f"a={a}, b={b}" <30> ) <31> ) <32> logger.debug(f"Affine Cipher returned {len(candidates)} candidates") <33> return candidates <34>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.affine.Affine plaintext_probability(translated: str) -> float decrypt(text: str, a_inv: int, b: int, m: int) -> str at: ciphey.basemods.Crackers.affine.Affine.__init__ self.alphabet_length = len(self.group) self.plaintext_prob_threshold = 0.01 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: ciphey.iface._modules.Cracker attemptCrack(self, ctext: T) -> List[CrackResult] at: ciphey.mathsHelper mathsHelper() at: ciphey.mathsHelper.mathsHelper gcd(a, b) -> int mod_inv(a: int, m: int) -> Optional[int] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 2=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 3=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 4=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 5=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 6=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 7=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 8=========== # module: ciphey.basemods.Searchers.astar adjacency_list = { "A": [("B", 1), ("C", 3), ("D", 7)], "B": [("D", 5)], "C": [("D", 12)], } A = Node(1) B = Node(7) C = Node(9) D = Node(16) A.edges = [(B, 1), (C, 3), (D, 7)] B.edges = [(D, 5)] C.edges = [(D, 12)] # TODO use a dictionary comprehension to make this adjacency_list = { A: A.edges, B: B.edges, C: C.edges, } graph1 = Graph(adjacency_list) graph1.a_star_algorithm(A, D) """ + Maybe after it - Maybe after it """ ===========changed ref 9=========== # module: tests.integration class testIntegration(unittest.TestCase): def test_integration_charlesBabbage(self): """ I had a bug with this exact string Bug is that chi squared does not score this as True + """ - """ text = """Charles Babbage, FRS (26 December 1791 - 18 October 1871) was an English mathematician, philosopher, inventor and mechanical engineer who originated the concept of a programmable computer. Considered a "father of the computer", Babbage is credited with inventing the first mechanical computer that eventually led to more complex designs. Parts of his uncompleted mechanisms are on display in the London Science Museum. In 1991, a perfectly functioning difference engine was constructed from Babbage's original plans. Built to tolerances achievable in the 19th century, the success of the finished engine indicated that Babbage's machine would have worked. Nine years later, the Science Museum completed the printer Babbage had designed for the difference engine.""" lc = LanguageChecker.Checker() result = lc.check(text) self.assertEqual(result, True)
ciphey.basemods.Crackers.affine/Affine.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<6>:<add> "group": ParamSpec( <del> "group": ciphey.iface.ParamSpec(
# module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: <0> return { <1> "expected": 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 alphabet", <8> req=False, <9> default="abcdefghijklmnopqrstuvwxyz", <10> ), <11> } <12>
===========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.Crackers.affine @registry.register class Affine(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: """ Brute forces all the possible combinations of a and b to attempt to crack the cipher. """ logger.trace("Attempting affine") candidates = [] # a and b are coprime if gcd(a,b) is 1. possible_a = [ a + for a in range(1, self.alphabet_length) - for a in range(1, self.ALPHABET_LENGTH) + if mathsHelper.gcd(a, self.alphabet_length) == 1 - if mathsHelper.gcd(a, self.ALPHABET_LENGTH) == 1 ] logger.debug( + f"Trying Affine Cracker with {len(possible_a)} a-values and {self.alphabet_length} b-values" - f"Trying Affine Cracker with {len(possible_a)} a-values and {self.ALPHABET_LENGTH} b-values" ) for a in possible_a: + a_inv = mathsHelper.mod_inv(a, self.alphabet_length) - a_inv = mathsHelper.mod_inv(a, self.ALPHABET_LENGTH) # If there is no inverse, we cannot decrypt the text if a_inv is None: continue + for b in range(self.alphabet_length): - for b in range(self.ALPHABET_LENGTH): # Pass in lowered text. This means that we expect alphabets to not contain both 'a' and 'A'. + translated = self.decrypt(ctext.lower(), a_inv, b, self.alphabet_length) - translated = self.decrypt(ctext.lower(), a_inv, b, self.ALPHABET_LENGTH) candidate_probability = self.plaintext_probability(translated) + if candidate_probability > self.plaintext</s> ===========changed ref 1=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 <s>LENGTH) candidate_probability = self.plaintext_probability(translated) + if candidate_probability > self.plaintext_prob_threshold: - if candidate_probability > self.PLAINTEXT_PROB_THRESHOLD: candidates.append( CrackResult( value=fix_case(translated, ctext), key_info=f"a={a}, b={b}" ) ) logger.debug(f"Affine Cipher returned {len(candidates)} candidates") return candidates ===========changed ref 2=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 4=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 5=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 6=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 7=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 8=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 9=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True
ciphey.basemods.Crackers.affine/Affine.__init__
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<3>:<add> self.alphabet_length = len(self.group) <del> self.ALPHABET_LENGTH = len(self.group) <5>:<add> self.plaintext_prob_threshold = 0.01 <del> self.PLAINTEXT_PROB_THRESHOLD = 0.01
# module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): <0> super().__init__(config) <1> self.group = list(self._params()["group"]) <2> self.expected = config.get_resource(self._params()["expected"]) <3> self.ALPHABET_LENGTH = len(self.group) <4> self.cache = config.cache <5> self.PLAINTEXT_PROB_THRESHOLD = 0.01 <6>
===========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) ===========changed ref 0=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 1=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: """ Brute forces all the possible combinations of a and b to attempt to crack the cipher. """ logger.trace("Attempting affine") candidates = [] # a and b are coprime if gcd(a,b) is 1. possible_a = [ a + for a in range(1, self.alphabet_length) - for a in range(1, self.ALPHABET_LENGTH) + if mathsHelper.gcd(a, self.alphabet_length) == 1 - if mathsHelper.gcd(a, self.ALPHABET_LENGTH) == 1 ] logger.debug( + f"Trying Affine Cracker with {len(possible_a)} a-values and {self.alphabet_length} b-values" - f"Trying Affine Cracker with {len(possible_a)} a-values and {self.ALPHABET_LENGTH} b-values" ) for a in possible_a: + a_inv = mathsHelper.mod_inv(a, self.alphabet_length) - a_inv = mathsHelper.mod_inv(a, self.ALPHABET_LENGTH) # If there is no inverse, we cannot decrypt the text if a_inv is None: continue + for b in range(self.alphabet_length): - for b in range(self.ALPHABET_LENGTH): # Pass in lowered text. This means that we expect alphabets to not contain both 'a' and 'A'. + translated = self.decrypt(ctext.lower(), a_inv, b, self.alphabet_length) - translated = self.decrypt(ctext.lower(), a_inv, b, self.ALPHABET_LENGTH) candidate_probability = self.plaintext_probability(translated) + if candidate_probability > self.plaintext</s> ===========changed ref 2=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 <s>LENGTH) candidate_probability = self.plaintext_probability(translated) + if candidate_probability > self.plaintext_prob_threshold: - if candidate_probability > self.PLAINTEXT_PROB_THRESHOLD: candidates.append( CrackResult( value=fix_case(translated, ctext), key_info=f"a={a}, b={b}" ) ) logger.debug(f"Affine Cipher returned {len(candidates)} candidates") return candidates ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 4=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 5=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 6=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 7=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 8=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 9=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param }
ciphey.basemods.Decoders.galactic/Galactic.decode
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<1>:<add> Takes a string written in the 'Standard Galactic Alphabet' <del> Takes a string written in the 'Standard Galactic Alphabet' <4>:<add> logger.trace("Attempting Standard Galactic Alphabet decoder") <del> logger.trace("Attempting Standard Galactic Alphabet Decoder") <18>:<add> "No matching galactic alphabet letters found. Skipping galactic decoder" <del> "No matching galactic alphabet letters found. Skipping galactic decoder..."
# module: ciphey.basemods.Decoders.galactic @registry.register + class Galactic(Decoder[str]): - 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> logger.trace("Attempting Standard Galactic Alphabet Decoder") <5> <6> # To avoid complications, only move forward with the decoding if we can <7> # reasonably assume that the input string is written in the galactic alphabet <8> galactic_matches = 0 <9> for symbol in self.GALACTIC_DICT.keys(): <10> # These symbols are assumed to be frequent enough in regular <11> # text to be skipped when counting the matches. All others are counted. <12> if symbol in ctext and symbol not in ["!", "|"]: <13> galactic_matches += 1 <14> else: <15> continue <16> if galactic_matches == 0: <17> logger.trace( <18> "No matching galactic alphabet letters found. Skipping galactic decoder..." <19> ) <20> return None <21> logger.trace(f"{galactic_matches} galactic alphabet letters found. ") <22> <23> result = "" <24> # Take out the problematic characters consisting of multiple symbols <25> ctext = ( <26> ctext.replace("||", "|") <27> .replace("/", "") <28> .replace("¡", "") <29> .replace(" ̣ ", "") <30> .replace("̇", "x") <31> ) <32> logger.trace(f"Modified string is {ctext}") <33> <34> for letter in ctext: <35> if letter in self.GALACTIC_DICT.keys(): <36> # Match every letter of the input to its galactic counterpoint <37> result += self.GALACTIC_DICT[letter] <38> else: <39> # If the current character is not</s>
===========below chunk 0=========== # module: ciphey.basemods.Decoders.galactic @registry.register + class Galactic(Decoder[str]): - class Galactic(Decoder[str, str]): def decode(self, ctext: T) -> Optional[U]: # offset: 1 # just accept it as-is (useful for numbers, punctuation,...) result += letter # Remove the trailing space (appearing as a leading space) # from the x that results from the diacritic replacement result = result.replace("x ", "x") logger.trace(f"Decoded string is {result}") return result ===========unchanged ref 0=========== at: ciphey.basemods.Decoders.galactic.Galactic.__init__ self.GALACTIC_DICT = config.get_resource(self._params()["dict"], Translation) at: ciphey.iface._modules T = TypeVar("T") U = TypeVar("U") at: ciphey.iface._modules.Decoder decode(self, ctext: T) -> Optional[U] ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 2=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 3=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 4=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 5=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 6=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 7=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 8=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 9=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 10=========== # module: ciphey.basemods.Searchers.astar adjacency_list = { "A": [("B", 1), ("C", 3), ("D", 7)], "B": [("D", 5)], "C": [("D", 12)], } A = Node(1) B = Node(7) C = Node(9) D = Node(16) A.edges = [(B, 1), (C, 3), (D, 7)] B.edges = [(D, 5)] C.edges = [(D, 12)] # TODO use a dictionary comprehension to make this adjacency_list = { A: A.edges, B: B.edges, C: C.edges, } graph1 = Graph(adjacency_list) graph1.a_star_algorithm(A, D) """ + Maybe after it - Maybe after it """
ciphey.basemods.Decoders.unicode/Utf8.decode
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> """ <add> Performs UTF-8 decoding <add> """ <add> logger.trace("Attempting UTF-8 decoder") <del> logger.trace("Attempting utf-8 decode") <1>:<add> result = "" <2>:<add> result = ctext.decode("utf-8") <del> res = text.decode("utf8") <3>:<add> if result != ctext: <add> logger.debug(f"UTF-8 successful, returning '{result}'") <add> return result <add> else: <add> return None <add> except Exception: <del> logger.debug(f"utf-8 decode gave '{res}'") <4>:<del> return res if len(res) != 0 else None <5>:<del> except UnicodeDecodeError: <6>:<del> logger.trace("utf-8 decode failed")
# module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): + def decode(self, ctext: T) -> Optional[U]: - def decode(self, text: bytes) -> Optional[str]: <0> logger.trace("Attempting utf-8 decode") <1> try: <2> res = text.decode("utf8") <3> logger.debug(f"utf-8 decode gave '{res}'") <4> return res if len(res) != 0 else None <5> except UnicodeDecodeError: <6> logger.trace("utf-8 decode failed") <7> return None <8>
===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 2=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 3=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 4=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 5=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 6=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 7=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 8=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 9=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 10=========== # module: ciphey.basemods.Searchers.astar adjacency_list = { "A": [("B", 1), ("C", 3), ("D", 7)], "B": [("D", 5)], "C": [("D", 12)], } A = Node(1) B = Node(7) C = Node(9) D = Node(16) A.edges = [(B, 1), (C, 3), (D, 7)] B.edges = [(D, 5)] C.edges = [(D, 12)] # TODO use a dictionary comprehension to make this adjacency_list = { A: A.edges, B: B.edges, C: C.edges, } graph1 = Graph(adjacency_list) graph1.a_star_algorithm(A, D) """ + Maybe after it - Maybe after it """ ===========changed ref 11=========== # module: tests.integration class testIntegration(unittest.TestCase): def test_integration_charlesBabbage(self): """ I had a bug with this exact string Bug is that chi squared does not score this as True + """ - """ text = """Charles Babbage, FRS (26 December 1791 - 18 October 1871) was an English mathematician, philosopher, inventor and mechanical engineer who originated the concept of a programmable computer. Considered a "father of the computer", Babbage is credited with inventing the first mechanical computer that eventually led to more complex designs. Parts of his uncompleted mechanisms are on display in the London Science Museum. In 1991, a perfectly functioning difference engine was constructed from Babbage's original plans. Built to tolerances achievable in the 19th century, the success of the finished engine indicated that Babbage's machine would have worked. Nine years later, the Science Museum completed the printer Babbage had designed for the difference engine.""" lc = LanguageChecker.Checker() result = lc.check(text) self.assertEqual(result, True)
ciphey.basemods.Decoders.unicode/Utf8.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> return None <del> pass
# module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: <0> pass <1>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._modules.Decoder __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): + def decode(self, ctext: T) -> Optional[U]: - def decode(self, text: bytes) -> Optional[str]: + """ + Performs UTF-8 decoding + """ + logger.trace("Attempting UTF-8 decoder") - logger.trace("Attempting utf-8 decode") + result = "" try: + result = ctext.decode("utf-8") - res = text.decode("utf8") + if result != ctext: + logger.debug(f"UTF-8 successful, returning '{result}'") + return result + else: + return None + except Exception: - logger.debug(f"utf-8 decode gave '{res}'") - return res if len(res) != 0 else None - except UnicodeDecodeError: - logger.trace("utf-8 decode failed") return None ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 2=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 3=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 4=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 5=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 6=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 7=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 8=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 9=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 10=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 11=========== # module: ciphey.basemods.Searchers.astar adjacency_list = { "A": [("B", 1), ("C", 3), ("D", 7)], "B": [("D", 5)], "C": [("D", 12)], } A = Node(1) B = Node(7) C = Node(9) D = Node(16) A.edges = [(B, 1), (C, 3), (D, 7)] B.edges = [(D, 5)] C.edges = [(D, 12)] # TODO use a dictionary comprehension to make this adjacency_list = { A: A.edges, B: B.edges, C: C.edges, } graph1 = Graph(adjacency_list) graph1.a_star_algorithm(A, D) """ + Maybe after it - Maybe after it """
ciphey.basemods.Searchers.ausearch/AuSearch.get_decoders_for
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> ret = registry[Decoder[t]] <del> ret = [j for i in registry[Decoder][t].values() for j in i]
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): <0> ret = [j for i in registry[Decoder][t].values() for j in i] <1> ret.sort(key=lambda x: x.priority(), reverse=True) <2> return ret <3>
===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 2=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 3=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 4=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 5=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 6=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 7=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 8=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 9=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 10=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 11=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): + def decode(self, ctext: T) -> Optional[U]: - def decode(self, text: bytes) -> Optional[str]: + """ + Performs UTF-8 decoding + """ + logger.trace("Attempting UTF-8 decoder") - logger.trace("Attempting utf-8 decode") + result = "" try: + result = ctext.decode("utf-8") - res = text.decode("utf8") + if result != ctext: + logger.debug(f"UTF-8 successful, returning '{result}'") + return result + else: + return None + except Exception: - logger.debug(f"utf-8 decode gave '{res}'") - return res if len(res) != 0 else None - except UnicodeDecodeError: - logger.trace("utf-8 decode failed") return None ===========changed ref 12=========== # module: ciphey.basemods.Searchers.astar adjacency_list = { "A": [("B", 1), ("C", 3), ("D", 7)], "B": [("D", 5)], "C": [("D", 12)], } A = Node(1) B = Node(7) C = Node(9) D = Node(16) A.edges = [(B, 1), (C, 3), (D, 7)] B.edges = [(D, 5)] C.edges = [(D, 12)] # TODO use a dictionary comprehension to make this adjacency_list = { A: A.edges, B: B.edges, C: C.edges, } graph1 = Graph(adjacency_list) graph1.a_star_algorithm(A, D) """ + Maybe after it - Maybe after it """
ciphey.basemods.Searchers.ausearch/AuSearch.expand_decodings
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<14>:<add> logger.trace("Nesting encodings") <del> logger.trace(f"Nesting encodings")
# module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: Node) -> None: <0> val = node.level.result.value <1> <2> for decoder in self.get_decoders_for(type(val)): <3> inst = self._config()(decoder) <4> res = inst(val) <5> if res is None: <6> continue <7> try: <8> new_node = Node.decoding( <9> config=self._config(), route=inst, result=res, source=node <10> ) <11> except DuplicateNode: <12> continue <13> <14> logger.trace(f"Nesting encodings") <15> self.recursive_expand(new_node, False) <16>
===========changed ref 0=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 2=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 4=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 5=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 6=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 7=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 8=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 9=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 10=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 11=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True ===========changed ref 12=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): + def decode(self, ctext: T) -> Optional[U]: - def decode(self, text: bytes) -> Optional[str]: + """ + Performs UTF-8 decoding + """ + logger.trace("Attempting UTF-8 decoder") - logger.trace("Attempting utf-8 decode") + result = "" try: + result = ctext.decode("utf-8") - res = text.decode("utf8") + if result != ctext: + logger.debug(f"UTF-8 successful, returning '{result}'") + return result + else: + return None + except Exception: - logger.debug(f"utf-8 decode gave '{res}'") - return res if len(res) != 0 else None - except UnicodeDecodeError: - logger.trace("utf-8 decode failed") return None
ciphey.basemods.Crackers.rot47/Rot47.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<1>:<add> "expected": ParamSpec( <del> "expected": ciphey.iface.ParamSpec( <6>:<add> "group": ParamSpec( <del> "group": ciphey.iface.ParamSpec( <9>:<add> default="""!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""", <del> default="""!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""", <11>:<add> "p_value": ParamSpec( <del> "p_value": ciphey.iface.ParamSpec(
# module: ciphey.basemods.Crackers.rot47 @registry.register + class Rot47(Cracker[str]): - class Rot47(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 ROT47 cipher alphabet", <8> req=False, <9> default="""!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""", <10> ), <11> "p_value": ciphey.iface.ParamSpec( <12> desc="The p-value to use for standard frequency analysis", <13> req=False, <14> default=0.01, <15> ) <16> # TODO: add "filter" param <17> } <18>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 2=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 3=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 4=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 6=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 7=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 8=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 9=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 10=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 11=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: Node) -> None: val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue + logger.trace("Nesting encodings") - logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False) ===========changed ref 12=========== # module: ciphey.iface._config class Cache: def mark_ctext(self, ctext: Any) -> bool: + if (isinstance(ctext, str) or isinstance(ctext, bytes)) and len(ctext) < 4: - if (type(ctext) == str or type(ctext) == bytes) and len(ctext) < 4: logger.trace(f"Candidate {ctext.__repr__()} too short!") return False if ctext in self._cache: logger.trace(f"Deduped {ctext.__repr__()}") return False logger.trace(f"New ctext {ctext.__repr__()}") self._cache[ctext] = {} return True
ciphey.basemods.Crackers.hash/beta
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<9>:<del> else: <10>:<add> return None <del> return None
# module: ciphey.basemods.Crackers.hash def beta(ctext, hashtype): <0> try: <1> response = requests.get( <2> "https://hashtoolkit.com/reverse-hash/?hash=", ctext, timeout=5 <3> ).text <4> except requests.exceptions.ReadTimeout as e: <5> logger.debug(f"Beta failed timeout {e}") <6> match = re.search(r'/generate-hash/?text=.*?"', response) <7> if match: <8> return match.group(1) <9> else: <10> return None <11>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.hash.beta response = requests.get( "https://hashtoolkit.com/reverse-hash/?hash=", ctext, timeout=5 ).text at: re search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] search(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] at: requests.api get(url: Union[Text, bytes], params: Optional[ Union[ SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType], Tuple[_ParamsMappingKeyType, _ParamsMappingValueType], Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]], Union[Text, bytes], ] ]=..., **kwargs) -> Response at: requests.exceptions ReadTimeout(*args, **kwargs) at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] at: typing.Match pos: int endpos: int lastindex: Optional[int] lastgroup: Optional[AnyStr] string: AnyStr re: Pattern[AnyStr] group(group1: Union[str, int], group2: Union[str, int], /, *groups: Union[str, int]) -> Tuple[AnyStr, ...] group(group: Union[str, int]=..., /) -> AnyStr ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 2=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 3=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 4=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 5=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 6=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 7=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 8=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 9=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 10=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param }
ciphey.basemods.Crackers.hash/HashBuster.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> return None <del> pass
# module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: <0> pass <1>
===========unchanged ref 0=========== at: ciphey.iface._modules T = TypeVar("T") CrackInfo(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker getInfo(self, ctext: T) -> CrackInfo ===========changed ref 0=========== # module: ciphey.basemods.Crackers.hash def beta(ctext, hashtype): try: response = requests.get( "https://hashtoolkit.com/reverse-hash/?hash=", ctext, timeout=5 ).text except requests.exceptions.ReadTimeout as e: logger.debug(f"Beta failed timeout {e}") match = re.search(r'/generate-hash/?text=.*?"', response) if match: return match.group(1) - else: + return None - return None ===========changed ref 1=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 2=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 4=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 5=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 7=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 8=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 9=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 10=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 11=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 12=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: Node) -> None: val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue + logger.trace("Nesting encodings") - logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False)
ciphey.basemods.Crackers.hash/HashBuster.attemptCrack
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> logger.debug("Starting to crack hashes") <del> logger.debug(f"Starting to crack hashes")
# module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: T) -> List[CrackResult]: <0> logger.debug(f"Starting to crack hashes") <1> result = False <2> <3> candidates = [] <4> if len(ctext) == 32: <5> for api in md5: <6> r = api(ctext, "md5") <7> if result is not None or r is not None: <8> logger.trace("MD5 returns True {r}") <9> candidates.append(result, "MD5") <10> elif len(ctext) == 40: <11> for api in sha1: <12> r = api(ctext, "sha1") <13> if result is not None and r is not None: <14> logger.trace("sha1 returns true") <15> candidates.append(result, "SHA1") <16> elif len(ctext) == 64: <17> for api in sha256: <18> r = api(ctext, "sha256") <19> if result is not None and r is not None: <20> logger.trace("sha256 returns true") <21> candidates.append(result, "SHA256") <22> elif len(ctext) == 96: <23> for api in sha384: <24> r = api(ctext, "sha384") <25> if result is not None and r is not None: <26> logger.trace("sha384 returns true") <27> candidates.append(result, "SHA384") <28> elif len(ctext) == 128: <29> for api in sha512: <30> r = api(ctext, "sha512") <31> if result is not None and r is not None: <32> logger.trace("sha512 returns true") <33> candidates.append(result, "SHA512") <34> <35> # TODO what the fuck is this code? <36> logger.trace(f"Hash buster returning {result}") <37> </s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: T) -> List[CrackResult]: # offset: 1 return [CrackResult(value=candidates[0][0], misc_info=candidates[1][1])] ===========unchanged ref 0=========== at: ciphey.basemods.Crackers.hash md5 = [gamma, alpha, beta, theta, delta] sha1 = [alpha, beta, theta, delta] sha256 = [alpha, beta, theta] sha384 = [alpha, beta, theta] sha512 = [alpha, beta, theta] at: ciphey.basemods.Crackers.hash.HashBuster.attemptCrack result = False at: ciphey.iface._config Config() at: ciphey.iface._modules CrackResult(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 1=========== # module: ciphey.basemods.Crackers.hash def beta(ctext, hashtype): try: response = requests.get( "https://hashtoolkit.com/reverse-hash/?hash=", ctext, timeout=5 ).text except requests.exceptions.ReadTimeout as e: logger.debug(f"Beta failed timeout {e}") match = re.search(r'/generate-hash/?text=.*?"', response) if match: return match.group(1) - else: + return None - return None ===========changed ref 2=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 3=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 4=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 5=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 6=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 7=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 8=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 9=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 10=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 11=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 12=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param }
ciphey.basemods.Decoders.bases/gen_class
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<0>:<add> ns["_get_func"] = id_lambda(decoder) <del> ns["_get_func"] = ciphey.common.id_lambda(decoder) <2>:<add> ns["getParams"] = id_lambda(None) <del> ns["getParams"] = ciphey.common.id_lambda(None) <3>:<add> ns["getTarget"] = id_lambda(name) <del> ns["getTarget"] = ciphey.common.id_lambda(name) <4>:<add> ns["priority"] = id_lambda(priority) <del> ns["priority"] = ciphey.common.id_lambda(priority)
# module: ciphey.basemods.Decoders.bases def gen_class(name, decoder, priority, ns): <0> ns["_get_func"] = ciphey.common.id_lambda(decoder) <1> ns["decode"] = lambda self, ctext: _dispatch(self, ctext, self._get_func()) <2> ns["getParams"] = ciphey.common.id_lambda(None) <3> ns["getTarget"] = ciphey.common.id_lambda(name) <4> ns["priority"] = ciphey.common.id_lambda(priority) <5> ns["__init__"] = lambda self, config: super(type(self), self).__init__(config) <6>
===========unchanged ref 0=========== at: ciphey.basemods.Decoders.bases _dispatch(self: Any, ctext: str, func: Callable[[str], bytes]) -> Optional[bytes] at: ciphey.common id_lambda(value: Any) ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 2=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 4=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 5=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 7=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 8=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 9=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 10=========== # module: ciphey.basemods.Crackers.hash def beta(ctext, hashtype): try: response = requests.get( "https://hashtoolkit.com/reverse-hash/?hash=", ctext, timeout=5 ).text except requests.exceptions.ReadTimeout as e: logger.debug(f"Beta failed timeout {e}") match = re.search(r'/generate-hash/?text=.*?"', response) if match: return match.group(1) - else: + return None - return None ===========changed ref 11=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 12=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 13=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): def expand_decodings(self, node: Node) -> None: val = node.level.result.value for decoder in self.get_decoders_for(type(val)): inst = self._config()(decoder) res = inst(val) if res is None: continue try: new_node = Node.decoding( config=self._config(), route=inst, result=res, source=node ) except DuplicateNode: continue + logger.trace("Nesting encodings") - logger.trace(f"Nesting encodings") self.recursive_expand(new_node, False)
ciphey.basemods.Crackers.ascii_shift/Ascii_shift.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<1>:<add> "expected": ParamSpec( <del> "expected": ciphey.iface.ParamSpec( <6>:<add> "group": ParamSpec( <del> "group": ciphey.iface.ParamSpec( <11>:<add> "p_value": ParamSpec( <del> "p_value": ciphey.iface.ParamSpec(
# module: ciphey.basemods.Crackers.ascii_shift @registry.register + class Ascii_shift(Cracker[str]): - class Ascii_shift(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 ASCII shift cipher alphabet", <8> req=False, <9> default="""\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f""", <10> ), <11> "p_value": ciphey.iface.ParamSpec( <12> desc="The p-value to use for standard frequency analysis", <13> req=False, <14> default=0.01, <15> ) <16> # TODO: add "filter" param <17> } <18>
===========unchanged ref 0=========== at: ciphey.iface._config Config() at: ciphey.iface._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: Any) at: ciphey.iface._modules.Cracker __init__(config: Config) __init__(self, config: Config) ===========changed ref 0=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 1=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 2=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 3=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 4=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 5=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 6=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 7=========== # module: ciphey.basemods.Decoders.bases for name, (decoder, priority) in _bases.items(): t = types.new_class( name, + (Decoder[str],), - (ciphey.iface.Decoder[str, bytes],), exec_body=lambda x: gen_class(name, decoder, priority, x), ) + registry.register(t) - ciphey.iface.registry.register(t) ===========changed ref 8=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 9=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), } ===========changed ref 10=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): def __init__(self, config: Config): super().__init__(config) self.group = list(self._params()["group"]) self.expected = config.get_resource(self._params()["expected"]) + self.alphabet_length = len(self.group) - self.ALPHABET_LENGTH = len(self.group) self.cache = config.cache + self.plaintext_prob_threshold = 0.01 - self.PLAINTEXT_PROB_THRESHOLD = 0.01 ===========changed ref 11=========== # module: ciphey.basemods.Crackers.hash def beta(ctext, hashtype): try: response = requests.get( "https://hashtoolkit.com/reverse-hash/?hash=", ctext, timeout=5 ).text except requests.exceptions.ReadTimeout as e: logger.debug(f"Beta failed timeout {e}") match = re.search(r'/generate-hash/?text=.*?"', response) if match: return match.group(1) - else: + return None - return None ===========changed ref 12=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def strip_puncuation(text: str) -> str: - """Strips punctuation from a given string. - - Uses string.puncuation. - - Args: - text -> the text to strip puncuation from. - - Returns: - Returns string without puncuation. - - """ - text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( - "\n" - ) - return text - ===========changed ref 13=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param }
ciphey.basemods.Crackers.vigenere/Vigenere.getInfo
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<4>:<add> lambda: cipheycore.analyse_string( <add> ctext.lower(), self.keysize, self.group <add> ), <del> lambda: cipheycore.analyse_string(ctext.lower(), self.keysize, self.group), <20>:<add> "vigenere::likely_lens", <del> f"vigenere::likely_lens", <21>:<add> lambda: cipheycore.vigenere_likely_key_lens( <add> ctext.lower(), self.expected, self.group, self.detect_p_value <del> lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.detect_p_value), <22>:<add> ), <24>:<del> likely_lens_cpy = likely_lens <26>:<add> likely_lens = [i for i in likely_lens if i.len <= self.max_key_length] <del> likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH]
# module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - 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.lower(), self.keysize, self.group), <5> ) <6> <7> val = cipheycore.vigenere_detect(analysis, self.expected) <8> <9> logger.debug(f"Vigenere has likelihood {val}") <10> <11> return CrackInfo( <12> success_likelihood=val, <13> # TODO: actually calculate runtimes <14> success_runtime=1e-3, <15> failure_runtime=1e-2, <16> ) <17> <18> likely_lens = self.cache.get_or_update( <19> ctext, <20> f"vigenere::likely_lens", <21> lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.detect_p_value), <22> ) <23> <24> likely_lens_cpy = likely_lens <25> # Filter out the lens that make no sense <26> likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] <27> <28> for keysize in likely_lens: <29> # Store the analysis <30> analysis = self.cache.get_or_update( <31> ctext, f"vigenere::{keysize.len}", lambda: keysize.tab <32> ) <33> if len(likely_lens) == 0: <34> return CrackInfo( <35> success_likelihood=0, <36> # TODO: actually calculate runtimes <37> </s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: # offset: 1 failure_runtime=2e-2, ) logger.debug(f"Vigenere has likelihood {likely_lens[0].p_value} with lens {[i.len for i in likely_lens]}") return CrackInfo( success_likelihood=likely_lens[0].p_value, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) ===========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.detect_p_value = float(self._params()["detect_p_value"]) self.max_key_length = 16 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) ===========changed ref 0=========== + # module: ciphey.basemods.Decoders.morse_code + + ===========changed ref 1=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 2=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 3=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 4=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 5=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 6=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "morse_code" + ===========changed ref 7=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 8=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 9=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return { + "dict": ParamSpec( + desc="The morse code dictionary to use", + req=False, + default="cipheydists::translate::morse", + ) + } + ===========changed ref 10=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 11=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + def __init__(self, config: Config): + super().__init__(config) + self.MORSE_CODE_DICT = config.get_resource(self._params()["dict"], Translation) + self.MORSE_CODE_DICT_INV = {v: k for k, v in self.MORSE_CODE_DICT.items()} + ===========changed ref 12=========== # module: ciphey.basemods.Decoders.bases for name, (decoder, priority) in _bases.items(): t = types.new_class( name, + (Decoder[str],), - (ciphey.iface.Decoder[str, bytes],), exec_body=lambda x: gen_class(name, decoder, priority, x), ) + registry.register(t) - ciphey.iface.registry.register(t) ===========changed ref 13=========== # module: ciphey.mathsHelper class mathsHelper: + + @staticmethod + def strip_punctuation(text: str) -> str: + """Strips punctuation from a given string. + + Uses string.punctuation. + + Args: + text -> the text to strip punctuation from. + + Returns: + Returns string without punctuation. + """ + text: str = (str(text).translate(str.maketrans("", "", punctuation))).strip( + "\n" + ) + return text + ===========changed ref 14=========== # module: ciphey.basemods.Crackers.affine @registry.register class Affine(Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { "expected": ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), }
ciphey.basemods.Crackers.vigenere/Vigenere.attemptCrack
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<14>:<add> lambda: cipheycore.analyse_string( <del> lambda: cipheycore.analyse_string(message, self.keysize, self.group), <15>:<add> message, self.keysize, self.group <add> ), <16>:<add> ctext, <del> ctext <18>:<add> <del> else: <19>:<add> arrs = [] <del> arrs = [] <20>:<add> likely_lens = self.cache.get_or_update( <del> likely_lens = self.cache.get_or_update( <21>:<add> ctext, <del> ctext, <22>:<add> "vigenere::likely_lens", <del> f"vigenere::likely_lens", <23>:<add> lambda: cipheycore.vigenere_likely_key_lens( <add> message, self.expected, self.group <add> ), <add> ) <add> possible_lens = [i for i in likely_lens] <add> possible_lens.sort(key=lambda i: i.p_value) <add> logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") <add> # TODO: work out length <add> for i in possible_lens: <add> arrs.extend( <add> self.crackOne( <add>
# module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - 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(message, self.keysize, self.group), <15> ), <16> ctext <17> ) <18> else: <19> arrs = [] <20> likely_lens = self.cache.get_or_update( <21> ctext, <22> f"vigenere::likely_lens", <23> lambda: cipheycore.vigenere_likely_key_lens(message, self.expected, self.group), <24> ) <25> possible_lens = [i for i in likely_lens] <26> possible_lens.sort(key=lambda i: i.p_value) <27> logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") <28> # TODO: work out length <29> for i in possible_lens: <30> arrs.extend( <31> self.crackOne( <32> message, <33> self.cache.get_or_update( <34> ctext, <35> f"vigenere::{i.len}", <36> lambda: cipheycore.analyse_string(message, i.len, self.group), <37> ), <38> </s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 ) ) logger.debug(f"Vigenere returned {len(arrs)} candidates") return arrs ===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere 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.basemods.Crackers.vigenere.Vigenere.crackOne possible_keys = cipheycore.vigenere_crack( analysis, self.expected, self.group, self.p_value ) possible_keys = possible_keys[: self.clamp] 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(Cracker[str]): - 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.lower(), self.keysize, self.group), ) val = cipheycore.vigenere_detect(analysis, self.expected) logger.debug(f"Vigenere has likelihood {val}") return CrackInfo( success_likelihood=val, # TODO: actually calculate runtimes success_runtime=1e-3, failure_runtime=1e-2, ) likely_lens = self.cache.get_or_update( ctext, + "vigenere::likely_lens", - f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens( + ctext.lower(), self.expected, self.group, self.detect_p_value - lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.detect_p_value), + ), ) - likely_lens_cpy = likely_lens # Filter out the lens that make no sense + likely_lens = [i for i in likely_lens if i.len <= self.max_key_length] - likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] </s> ===========changed ref 1=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): def getInfo(self, ctext: str) -> CrackInfo: # offset: 1 <s> <del> likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] 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-3, failure_runtime=2e-2, ) + logger.debug( + f"Vigenere has likelihood {likely_lens[0].p_value} with lens {[i.len for i in likely_lens]}" - logger.debug(f"Vigenere has likelihood {likely_lens[0].p_value} with lens {[i.len for i in likely_lens]}") + ) return CrackInfo( success_likelihood=likely_lens[0].p_value, # TODO: actually calculate runtimes success_runtime=2e-4, failure_runtime=2e-4, ) ===========changed ref 2=========== + # module: ciphey.basemods.Decoders.morse_code + + ===========changed ref 3=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 4=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 5=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 6=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 7=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 8=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "morse_code" +
ciphey.basemods.Crackers.vigenere/Vigenere.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<1>:<add> "expected": ParamSpec( <del> "expected": ciphey.iface.ParamSpec( <6>:<add> "group": ParamSpec( <del> "group": ciphey.iface.ParamSpec( <11>:<add> "lower": ParamSpec( <del> "lower": ciphey.iface.ParamSpec( <16>:<add> "keysize": ParamSpec( <del> "keysize": ciphey.iface.ParamSpec( <20>:<add> "p_value": ParamSpec( <del> "p_value": ciphey.iface.ParamSpec( <25>:<add> "detect_p_value": ParamSpec( <del> "detect_p_value": ciphey.iface.ParamSpec( <30>:<add> "clamp": ParamSpec( <del> "clamp": ciphey.iface.ParamSpec(
# module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - 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.5, <24> ), <25> "detect_p_value": ciphey.iface.ParamSpec( <26> desc="The p-value to use for the detection of Vigenere length", <27> req=False, <28> default=0.01, <29> ), <30> "clamp": ciphey.iface.ParamSpec( <31> desc="The maximum number of candidates that can be returned per key len", <32> req=False, <33> default=10, <34> ), <35> } <36>
===========unchanged ref 0=========== at: ciphey.basemods.Crackers.vigenere.Vigenere.attemptCrack arrs = [] 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.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - 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( - lambda: cipheycore.analyse_string(message, self.keysize, self.group), + message, self.keysize, self.group + ), ), + ctext, - ctext ) + - else: + arrs = [] - arrs = [] + likely_lens = self.cache.get_or_update( - likely_lens = self.cache.get_or_update( + ctext, - ctext, + "vigenere::likely_lens", - f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens( + message, self.expected, self.group + ), + ) + possible_lens = [i for i in likely_lens] + possible_lens.sort(key=lambda i: i.p_value) + logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") + # TODO: work out length + for i in possible_lens: + arrs.extend( + self.c</s> ===========changed ref 1=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 <s> # TODO: work out length + for i in possible_lens: + arrs.extend( + self.crackOne( + message, + self.cache.get_or_update( + ctext, + f"vigenere::{i.len}", + lambda: cipheycore.analyse_string(message, i.len, self.group), + ), + ctext, + ) - lambda: cipheycore.vigenere_likely_key_lens(message, self.expected, self.group), ) - possible_lens = [i for i in likely_lens] - possible_lens.sort(key=lambda i: i.p_value) - logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") - # TODO: work out length - for i in possible_lens: - arrs.extend( - self.crackOne( - message, - self.cache.get_or_update( - ctext, - f"vigenere::{i.len}", - lambda: cipheycore.analyse_string(message, i.len, self.group), - ), - ctext - ) - ) + logger.debug(f"Vigenere returned {len(arrs)} candidates") - logger.debug(f"Vigenere returned {len(arrs)} candidates") + return arrs - return arrs ===========changed ref 2=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - 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.lower(), self.keysize, self.group), ) val = cipheycore.vigenere_detect(analysis, self.expected) logger.debug(f"Vigenere has likelihood {val}") return CrackInfo( success_likelihood=val, # TODO: actually calculate runtimes success_runtime=1e-3, failure_runtime=1e-2, ) likely_lens = self.cache.get_or_update( ctext, + "vigenere::likely_lens", - f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens( + ctext.lower(), self.expected, self.group, self.detect_p_value - lambda: cipheycore.vigenere_likely_key_lens(ctext.lower(), self.expected, self.group, self.detect_p_value), + ), ) - likely_lens_cpy = likely_lens # Filter out the lens that make no sense + likely_lens = [i for i in likely_lens if i.len <= self.max_key_length] - likely_lens = [i for i in likely_lens if i.len <= self.MAX_KEY_LENGTH] </s>
ciphey.basemods.Crackers.vigenere/Vigenere.__init__
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<2>:<add> if not isinstance(self.lower, bool): <del> if type(self.lower) != bool: <13>:<add> self.max_key_length = 16 <del> self.MAX_KEY_LENGTH = 16
# module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): + def __init__(self, config: Config): - 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 = float(self._params()["p_value"]) <11> self.detect_p_value = float(self._params()["detect_p_value"]) <12> self.clamp = int(self._params()["clamp"]) <13> self.MAX_KEY_LENGTH = 16 <14>
===========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._modules ParamSpec(typename: str, fields: Iterable[Tuple[str, Any]]=..., **kwargs: 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(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the caesar cipher alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), + "lower": ParamSpec( - "lower": ciphey.iface.ParamSpec( desc="Whether or not the ciphertext should be converted to lowercase first", req=False, default=True, ), + "keysize": ParamSpec( - "keysize": ciphey.iface.ParamSpec( desc="A key size that should be used. If not given, will attempt to work it out", req=False, ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for windowed frequency analysis", req=False, default=0.5, ), + "detect_p_value": ParamSpec( - "detect_p_value": ciphey.iface.ParamSpec( desc="The p-value to use for the detection of Vigenere length", req=False, default=0.01, ), + "clamp": ParamSpec( - "clamp": ciphey.iface.ParamSpec( desc="The maximum number of candidates that can be returned per key len", req=False, default=10,</s> ===========changed ref 1=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: # offset: 1 <s>( desc="The maximum number of candidates that can be returned per key len", req=False, default=10, ), } ===========changed ref 2=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - 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( - lambda: cipheycore.analyse_string(message, self.keysize, self.group), + message, self.keysize, self.group + ), ), + ctext, - ctext ) + - else: + arrs = [] - arrs = [] + likely_lens = self.cache.get_or_update( - likely_lens = self.cache.get_or_update( + ctext, - ctext, + "vigenere::likely_lens", - f"vigenere::likely_lens", + lambda: cipheycore.vigenere_likely_key_lens( + message, self.expected, self.group + ), + ) + possible_lens = [i for i in likely_lens] + possible_lens.sort(key=lambda i: i.p_value) + logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") + # TODO: work out length + for i in possible_lens: + arrs.extend( + self.c</s> ===========changed ref 3=========== # module: ciphey.basemods.Crackers.vigenere @registry.register + class Vigenere(Cracker[str]): - class Vigenere(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 <s> # TODO: work out length + for i in possible_lens: + arrs.extend( + self.crackOne( + message, + self.cache.get_or_update( + ctext, + f"vigenere::{i.len}", + lambda: cipheycore.analyse_string(message, i.len, self.group), + ), + ctext, + ) - lambda: cipheycore.vigenere_likely_key_lens(message, self.expected, self.group), ) - possible_lens = [i for i in likely_lens] - possible_lens.sort(key=lambda i: i.p_value) - logger.trace(f"Got possible lengths {[i.len for i in likely_lens]}") - # TODO: work out length - for i in possible_lens: - arrs.extend( - self.crackOne( - message, - self.cache.get_or_update( - ctext, - f"vigenere::{i.len}", - lambda: cipheycore.analyse_string(message, i.len, self.group), - ), - ctext - ) - ) + logger.debug(f"Vigenere returned {len(arrs)} candidates") - logger.debug(f"Vigenere returned {len(arrs)} candidates") + return arrs - return arrs
ciphey.basemods.Crackers.caesar/Caesar.attemptCrack
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<26>:<add> logger.trace("Filtering for better results") <del> logger.trace(f"Filtering for better results") <37>:<add> candidates.append( <add> CrackResult(value=fix_case(translated, ctext), key_info=candidate.key) <del> candidates.append(CrackResult(value=fix_case(translated
# module: ciphey.basemods.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: <0> logger.debug(f"Trying caesar cipher on {ctext}") <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=fix_case(translated</s>
===========below chunk 0=========== # module: ciphey.basemods.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 return candidates ===========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) ===========changed ref 0=========== + # module: ciphey.basemods.Decoders.leetspeak + + ===========changed ref 1=========== + # module: ciphey.basemods.Decoders.morse_code + + ===========changed ref 2=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 3=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 4=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 5=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "leetspeak" + ===========changed ref 6=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 7=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 8=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 9=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "morse_code" + ===========changed ref 10=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 11=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + def __init__(self, config: Config): + super().__init__(config) + self.translate = config.get_resource(self._params()["dict"], Translation) + ===========changed ref 12=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + def decode(self, ctext: T) -> Optional[U]: + for src, dst in self.translate.items(): + ctext = ctext.replace(src, dst) + return ctext + ===========changed ref 13=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 14=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return { + "dict": ParamSpec( + desc="The leetspeak dictionary to use", + req=False, + default="cipheydists::translate::leet", + ) + } + ===========changed ref 15=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return { + "dict": ParamSpec( + desc="The morse code dictionary to use", + req=False, + default="cipheydists::translate::morse", + ) + } + ===========changed ref 16=========== # module: ciphey.basemods.Searchers.ausearch @registry.register class AuSearch(Searcher): @lru_cache() # To save extra sorting def get_decoders_for(self, t: type): + ret = registry[Decoder[t]] - 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 17=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + def __init__(self, config: Config): + super().__init__(config) + self.MORSE_CODE_DICT = config.get_resource(self._params()["dict"], Translation) + self.MORSE_CODE_DICT_INV = {v: k for k, v in self.MORSE_CODE_DICT.items()} + ===========changed ref 18=========== # module: ciphey.basemods.Decoders.bases for name, (decoder, priority) in _bases.items(): t = types.new_class( name, + (Decoder[str],), - (ciphey.iface.Decoder[str, bytes],), exec_body=lambda x: gen_class(name, decoder, priority, x), ) + registry.register(t) - ciphey.iface.registry.register(t)
ciphey.basemods.Crackers.caesar/Caesar.getParams
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<1>:<add> "expected": ParamSpec( <del> "expected": ciphey.iface.ParamSpec( <6>:<add> "group": ParamSpec( <del> "group": ciphey.iface.ParamSpec( <11>:<add> "lower": ParamSpec( <del> "lower": ciphey.iface.ParamSpec( <16>:<add> "p_value": ParamSpec( <del> "p_value": ciphey.iface.ParamSpec(
# module: ciphey.basemods.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - 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.01, <20> ) <21> # TODO: add "filter" param <22> } <23>
===========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.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: logger.debug(f"Trying caesar cipher on {ctext}") # 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), ) logger.trace("Beginning cipheycore::caesar") possible_keys = cipheycore.caesar_crack( analysis, self.expected, self.group, self.p_value ) n_candidates = len(possible_keys) logger.debug(f"Caesar returned {n_candidates} candidates") if n_candidates == 0: + logger.trace("Filtering for better results") - 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=fix_case(translated, ctext), key_info=candidate.key) - candidates.append(Crack</s> ===========changed ref 1=========== # module: ciphey.basemods.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 <s>Result(value=fix_case(translated, ctext), key_info=candidate.key) - candidates.append(CrackResult(value=fix_case(translated, ctext), key_info=candidate.key)) + ) return candidates ===========changed ref 2=========== + # module: ciphey.basemods.Decoders.leetspeak + + ===========changed ref 3=========== + # module: ciphey.basemods.Decoders.morse_code + + ===========changed ref 4=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 5=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 6=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 7=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "leetspeak" + ===========changed ref 8=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 9=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 10=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 11=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "morse_code" + ===========changed ref 12=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 13=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + def __init__(self, config: Config): + super().__init__(config) + self.translate = config.get_resource(self._params()["dict"], Translation) + ===========changed ref 14=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + def decode(self, ctext: T) -> Optional[U]: + for src, dst in self.translate.items(): + ctext = ctext.replace(src, dst) + return ctext + ===========changed ref 15=========== # module: ciphey.iface._registry try: + from typing import get_args, get_origin - from typing import get_origin, get_args except ImportError: from typing_inspect import get_origin, get_args ===========changed ref 16=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return { + "dict": ParamSpec( + desc="The leetspeak dictionary to use", + req=False, + default="cipheydists::translate::leet", + ) + } + ===========changed ref 17=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: + return { + "dict": ParamSpec( + desc="The morse code dictionary to use", + req=False, + default="cipheydists::translate::morse", + ) + } +
ciphey.basemods.Crackers.caesar/Caesar.__init__
Modified
Ciphey~Ciphey
5544e945c591d063a2541fd40991c1f81b729575
Code cleanup (#510)
<2>:<add> if not isinstance(self.lower, bool): <del> if type(self.lower) != bool:
# module: ciphey.basemods.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): + def __init__(self, config: Config): - 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 = float(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.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): @staticmethod def getParams() -> Optional[Dict[str, ParamSpec]]: return { + "expected": ParamSpec( - "expected": ciphey.iface.ParamSpec( desc="The expected distribution of the plaintext", req=False, config_ref=["default_dist"], ), + "group": ParamSpec( - "group": ciphey.iface.ParamSpec( desc="An ordered sequence of chars that make up the caesar cipher alphabet", req=False, default="abcdefghijklmnopqrstuvwxyz", ), + "lower": ParamSpec( - "lower": ciphey.iface.ParamSpec( desc="Whether or not the ciphertext should be converted to lowercase first", req=False, default=True, ), + "p_value": ParamSpec( - "p_value": ciphey.iface.ParamSpec( desc="The p-value to use for standard frequency analysis", req=False, default=0.01, ) # TODO: add "filter" param } ===========changed ref 1=========== # module: ciphey.basemods.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: logger.debug(f"Trying caesar cipher on {ctext}") # 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), ) logger.trace("Beginning cipheycore::caesar") possible_keys = cipheycore.caesar_crack( analysis, self.expected, self.group, self.p_value ) n_candidates = len(possible_keys) logger.debug(f"Caesar returned {n_candidates} candidates") if n_candidates == 0: + logger.trace("Filtering for better results") - 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=fix_case(translated, ctext), key_info=candidate.key) - candidates.append(Crack</s> ===========changed ref 2=========== # module: ciphey.basemods.Crackers.caesar @registry.register + class Caesar(Cracker[str]): - class Caesar(ciphey.iface.Cracker[str]): def attemptCrack(self, ctext: str) -> List[CrackResult]: # offset: 1 <s>Result(value=fix_case(translated, ctext), key_info=candidate.key) - candidates.append(CrackResult(value=fix_case(translated, ctext), key_info=candidate.key)) + ) return candidates ===========changed ref 3=========== + # module: ciphey.basemods.Decoders.leetspeak + + ===========changed ref 4=========== + # module: ciphey.basemods.Decoders.morse_code + + ===========changed ref 5=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 6=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def priority() -> float: + return 0.05 + ===========changed ref 7=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): + @staticmethod + def score_utility() -> float: + return 1.5 + ===========changed ref 8=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "leetspeak" + ===========changed ref 9=========== # module: ciphey.basemods.Crackers.hash @registry.register + class HashBuster(Cracker[str]): - class HashBuster(ciphey.iface.Cracker[str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 10=========== # module: ciphey.basemods.Decoders.unicode @registry.register + class Utf8(Decoder[bytes]): - class Utf8(ciphey.iface.Decoder[bytes, str]): @staticmethod + def getParams() -> Optional[Dict[str, ParamSpec]]: - def getParams() -> Optional[Dict[str, Dict[str, Any]]]: + return None - pass ===========changed ref 11=========== # module: ciphey.basemods.Crackers.xor_single @registry.register + class XorSingle(Cracker[bytes]): - class XorSingle(ciphey.iface.Cracker[bytes]): - @staticmethod - def scoreUtility() -> float: - return 1.5 - ===========changed ref 12=========== + # module: ciphey.basemods.Decoders.morse_code + @registry.register + class Morse_code(Decoder[str]): + @staticmethod + def getTarget() -> str: + return "morse_code" + ===========changed ref 13=========== # module: ciphey.basemods.Checkers.gtest @registry.register class GTestChecker(Checker[str]): def check(self, text: T) -> Optional[str]: + logger.trace("Trying entropy checker") - logger.trace(f"Trying entropy checker") pass ===========changed ref 14=========== + # module: ciphey.basemods.Decoders.leetspeak + @registry.register + class Leetspeak(Decoder[str]): + def __init__(self, config: Config): + super().__init__(config) + self.translate = config.get_resource(self._params()["dict"], Translation) +