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.mathsHelper/mathsHelper.new_sort
Modified
Ciphey~Ciphey
c1303641f65518f0cefb97d1fe10050173fa362a
Can now upload to PyPi with Poetry + Blackened the codebase
<13>:<add> sorted_i = OrderedDict( <add> sorted(new_dict.items(), key=lambda x: x[1], reverse=True) <del> sorted_i = OrderedDict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)) <14>:<add> )
# module: ciphey.mathsHelper class mathsHelper: @staticmethod def new_sort(new_dict: dict) -> dict: <0> """Uses OrderedDict to sort a dictionary. <1> <2> I think it's faster than my implementation. <3> <4> Args: <5> new_dict -> the dictionary to sort <6> <7> Returns: <8> Returns the dict, but sorted. <9> <10> """ <11> # (f"d is {d}") <12> logger.debug(f"The old dictionary before new_sort() is {new_dict}") <13> sorted_i = OrderedDict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)) <14> logger.debug(f"The dictionary after new_sort() is {sorted_i}") <15> # sortedI = sort_dictionary(x) <16> return sorted_i <17>
===========unchanged ref 0=========== at: ciphey.mathsHelper.mathsHelper.sort_prob_table empty_dict: dict = {} empty_dict = {**empty_dict, **max_dict_pair} at: collections OrderedDict(map: Mapping[_KT, _VT], **kwargs: _VT) OrderedDict(**kwargs: _VT) OrderedDict(iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT)
ciphey.Decryptor.basicEncryption.vigenere/Vigenere.attemptHackWithKeyLength
Modified
Ciphey~Ciphey
c1303641f65518f0cefb97d1fe10050173fa362a
Can now upload to PyPi with Poetry + Blackened the codebase
<6>:<add> possible_keys = cipheycore.vigenere_crack( <add> ciphertext, expected, group, mostLikelyKeyLength <add> ) <del> possible_keys = cipheycore.vigenere_crack(ciphertext, expected, group, mostLikelyKeyLength) <16>:<add> decryptedText = cipheycore.vigenere_decrypt( <del> decryptedText = cipheycore.vigenere_decrypt(ciphertext, candidate.key, group) <17>:<add> ciphertext, candidate.key, group <add> )
# module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): <0> # Determine the most likely letters for each letter in the key: <1> ciphertext = ciphertext.lower() <2> <3> # Do core work <4> group = cipheydists.get_charset("english")["lcase"] <5> expected = cipheydists.get_dist("lcase") <6> possible_keys = cipheycore.vigenere_crack(ciphertext, expected, group, mostLikelyKeyLength) <7> n_keys = len(possible_keys) <8> <9> # Try all the feasible keys <10> for candidate in possible_keys: <11> nice_key = list(candidate.key) <12> # Create a possible key from the letters in allFreqScores: <13> if not self.SILENT_MODE: <14> print("Attempting with key: %s" % nice_key) <15> <16> decryptedText = cipheycore.vigenere_decrypt(ciphertext, candidate.key, group) <17> <18> if self.lc.checkLanguage(decryptedText): <19> print(f"AAAAAAAAAAAA {decryptedText}") <20> # Set the hacked ciphertext to the original casing: <21> origCase = [] <22> for i in range(len(ciphertext)): <23> if ciphertext[i].isupper(): <24> origCase.append(decryptedText[i].upper()) <25> else: <26> origCase.append(decryptedText[i].lower()) <27> decryptedText = "".join(origCase) <28> <29> # Check with user to see if the key has been found: <30> return { <31> "lc": self.lc, <32> "IsPlaintext?": True, <33> "Plaintext": decryptedText, <34> "Cipher": "Viginere", <35> </s>
===========below chunk 0=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # offset: 1 } # No English-looking decryption found, so return None: return None ===========unchanged ref 0=========== at: ciphey.Decryptor.basicEncryption.vigenere.Vigenere.__init__ self.SILENT_MODE = True # If set to True, program doesn't print anything. self.lc = lc at: languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool ===========changed ref 0=========== # module: ciphey.mathsHelper class mathsHelper: @staticmethod def new_sort(new_dict: dict) -> dict: """Uses OrderedDict to sort a dictionary. I think it's faster than my implementation. Args: new_dict -> the dictionary to sort Returns: Returns the dict, but sorted. """ # (f"d is {d}") logger.debug(f"The old dictionary before new_sort() is {new_dict}") + sorted_i = OrderedDict( + sorted(new_dict.items(), key=lambda x: x[1], reverse=True) - sorted_i = OrderedDict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)) + ) logger.debug(f"The dictionary after new_sort() is {sorted_i}") # sortedI = sort_dictionary(x) return sorted_i
ciphey.Decryptor.basicEncryption.basic_parent/BasicParent.decrypt
Modified
Ciphey~Ciphey
c1303641f65518f0cefb97d1fe10050173fa362a
Can now upload to PyPi with Poetry + Blackened the codebase
<24>:<add> <del>
# module: ciphey.Decryptor.basicEncryption.basic_parent class BasicParent: + - def decrypt(self, text): <0> self.text = text <1> from multiprocessing.dummy import Pool as ThreadPool <2> <3> pool = ThreadPool(16) <4> answers = pool.map(self.callDecrypt, self.list_of_objects) <5> <6> """for item in self.list_of_objects: <7> result = item.decrypt(text) <8> answers.append(result)""" <9> for answer in answers: <10> # adds the LC objects together <11> # self.lc = self.lc + answer["lc"] <12> if answer["IsPlaintext?"]: <13> return answer <14> <15> # so vigenere runs ages <16> # and you cant kill threads in a pool <17> # so i just run it last lol] <18> # <19> # Not anymore! #basedcore <20> <21> result = self.callDecrypt(self.vigenere) <22> if result["IsPlaintext?"]: <23> return result <24> <25> return { <26> "lc": self.lc, <27> "IsPlaintext?": False, <28> "Plaintext": None, <29> "Cipher": None, <30> "Extra Information": None, <31> } <32>
===========unchanged ref 0=========== at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent callDecrypt(obj) at: ciphey.Decryptor.basicEncryption.basic_parent.BasicParent.__init__ self.lc = lc self.vigenere = vi.Vigenere(self.lc) self.list_of_objects = [self.caesar, self.reverse, self.pig, self.trans] at: multiprocessing.dummy Pool(processes: Optional[int]=..., initializer: Optional[Callable[..., Any]]=..., initargs: Iterable[Any]=...) -> Any ===========changed ref 0=========== # module: ciphey.mathsHelper class mathsHelper: @staticmethod def new_sort(new_dict: dict) -> dict: """Uses OrderedDict to sort a dictionary. I think it's faster than my implementation. Args: new_dict -> the dictionary to sort Returns: Returns the dict, but sorted. """ # (f"d is {d}") logger.debug(f"The old dictionary before new_sort() is {new_dict}") + sorted_i = OrderedDict( + sorted(new_dict.items(), key=lambda x: x[1], reverse=True) - sorted_i = OrderedDict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)) + ) logger.debug(f"The dictionary after new_sort() is {sorted_i}") # sortedI = sort_dictionary(x) return sorted_i ===========changed ref 1=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key: ciphertext = ciphertext.lower() # Do core work group = cipheydists.get_charset("english")["lcase"] expected = cipheydists.get_dist("lcase") + possible_keys = cipheycore.vigenere_crack( + ciphertext, expected, group, mostLikelyKeyLength + ) - possible_keys = cipheycore.vigenere_crack(ciphertext, expected, group, mostLikelyKeyLength) n_keys = len(possible_keys) # Try all the feasible keys for candidate in possible_keys: nice_key = list(candidate.key) # Create a possible key from the letters in allFreqScores: if not self.SILENT_MODE: print("Attempting with key: %s" % nice_key) + decryptedText = cipheycore.vigenere_decrypt( - decryptedText = cipheycore.vigenere_decrypt(ciphertext, candidate.key, group) + ciphertext, candidate.key, group + ) if self.lc.checkLanguage(decryptedText): print(f"AAAAAAAAAAAA {decryptedText}") # Set the hacked ciphertext to the original casing: origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = "".join(origCase) # Check with user to see if the key has been found: return { "</s> ===========changed ref 2=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # offset: 1 <s>origCase) # Check with user to see if the key has been found: return { "lc": self.lc, "IsPlaintext?": True, "Plaintext": decryptedText, "Cipher": "Viginere", "Extra Information": f"The key used is {nice_key}", } # No English-looking decryption found, so return None: return None
ciphey.__main__/Ciphey.decrypt_normal
Modified
Ciphey~Ciphey
c1303641f65518f0cefb97d1fe10050173fa362a
Can now upload to PyPi with Poetry + Blackened the codebase
<24>:<add> print(ret["Plaintext"]) <del> print(ret['Plaintext'])
# module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: <0> """Called by one_level_of_decryption <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> bar -> whether or not to use alive_Bar <6> <7> Returns: <8> None, but prints. <9> <10> """ <11> logger.debug(f"In decrypt_normal") <12> for key, val in self.what_to_choose.items(): <13> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <14> if not isinstance(key, str): <15> key.setProbTable(val) <16> ret: dict = key.decrypt(self.text) <17> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <18> logger.debug( <19> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <20> ) <21> <22> if ret["IsPlaintext?"]: <23> logger.debug(f"Ret is plaintext") <24> print(ret['Plaintext']) <25> if self.cipher: <26> if ret["Extra Information"] is not None: <27> print( <28> "The cipher used is", <29> ret["Cipher"] + ".", <30> ret["Extra Information"] + ".", <31> ) <32> else: <33> print("The cipher used is " + ret["Cipher"] + ".") <34> return ret <35> <36> logger.debug("No encryption found") <37> print( <38> """No encryption found. Here are some tips to help crack the cipher: <39> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. </s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: # offset: 1 Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey.__init__ self.text: str = text self.cipher = cipher self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) ===========changed ref 0=========== # module: ciphey.mathsHelper class mathsHelper: @staticmethod def new_sort(new_dict: dict) -> dict: """Uses OrderedDict to sort a dictionary. I think it's faster than my implementation. Args: new_dict -> the dictionary to sort Returns: Returns the dict, but sorted. """ # (f"d is {d}") logger.debug(f"The old dictionary before new_sort() is {new_dict}") + sorted_i = OrderedDict( + sorted(new_dict.items(), key=lambda x: x[1], reverse=True) - sorted_i = OrderedDict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)) + ) logger.debug(f"The dictionary after new_sort() is {sorted_i}") # sortedI = sort_dictionary(x) return sorted_i ===========changed ref 1=========== # module: ciphey.Decryptor.basicEncryption.basic_parent class BasicParent: + - def decrypt(self, text): self.text = text from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(16) answers = pool.map(self.callDecrypt, self.list_of_objects) """for item in self.list_of_objects: result = item.decrypt(text) answers.append(result)""" for answer in answers: # adds the LC objects together # self.lc = self.lc + answer["lc"] if answer["IsPlaintext?"]: return answer # so vigenere runs ages # and you cant kill threads in a pool # so i just run it last lol] # # Not anymore! #basedcore result = self.callDecrypt(self.vigenere) if result["IsPlaintext?"]: return result + - return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 2=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key: ciphertext = ciphertext.lower() # Do core work group = cipheydists.get_charset("english")["lcase"] expected = cipheydists.get_dist("lcase") + possible_keys = cipheycore.vigenere_crack( + ciphertext, expected, group, mostLikelyKeyLength + ) - possible_keys = cipheycore.vigenere_crack(ciphertext, expected, group, mostLikelyKeyLength) n_keys = len(possible_keys) # Try all the feasible keys for candidate in possible_keys: nice_key = list(candidate.key) # Create a possible key from the letters in allFreqScores: if not self.SILENT_MODE: print("Attempting with key: %s" % nice_key) + decryptedText = cipheycore.vigenere_decrypt( - decryptedText = cipheycore.vigenere_decrypt(ciphertext, candidate.key, group) + ciphertext, candidate.key, group + ) if self.lc.checkLanguage(decryptedText): print(f"AAAAAAAAAAAA {decryptedText}") # Set the hacked ciphertext to the original casing: origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = "".join(origCase) # Check with user to see if the key has been found: return { "</s> ===========changed ref 3=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # offset: 1 <s>origCase) # Check with user to see if the key has been found: return { "lc": self.lc, "IsPlaintext?": True, "Plaintext": decryptedText, "Cipher": "Viginere", "Extra Information": f"The key used is {nice_key}", } # No English-looking decryption found, so return None: return None
ciphey.languageCheckerMod.chisquared/chiSquared.__init__
Modified
Ciphey~Ciphey
c1303641f65518f0cefb97d1fe10050173fa362a
Can now upload to PyPi with Poetry + Blackened the codebase
<11>:<add> self.chiSquaredSignificanceThreshold = 0.001 # The p value that we reject below <del> self.chiSquaredSignificanceThreshold = 0.001 # The p value that we reject below
# module: ciphey.languageCheckerMod.chisquared class chiSquared: def __init__(self): <0> self.language = cipheydists.get_dist("twist") <1> self.average = 0.0 <2> self.totalDone = 0.0 <3> self.oldAverage = 0.0 <4> self.mh = mh.mathsHelper() <5> self.highestLanguage = "" <6> self.totalChi = 0.0 <7> self.totalEqual = False <8> self.chisAsaList = [] <9> <10> # these are settings that may impact how the program works overall <11> self.chiSquaredSignificanceThreshold = 0.001 # The p value that we reject below <12>
===========unchanged ref 0=========== at: ciphey.mathsHelper mathsHelper() ===========changed ref 0=========== # module: ciphey.mathsHelper class mathsHelper: @staticmethod def new_sort(new_dict: dict) -> dict: """Uses OrderedDict to sort a dictionary. I think it's faster than my implementation. Args: new_dict -> the dictionary to sort Returns: Returns the dict, but sorted. """ # (f"d is {d}") logger.debug(f"The old dictionary before new_sort() is {new_dict}") + sorted_i = OrderedDict( + sorted(new_dict.items(), key=lambda x: x[1], reverse=True) - sorted_i = OrderedDict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)) + ) logger.debug(f"The dictionary after new_sort() is {sorted_i}") # sortedI = sort_dictionary(x) return sorted_i ===========changed ref 1=========== # module: ciphey.Decryptor.basicEncryption.basic_parent class BasicParent: + - def decrypt(self, text): self.text = text from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(16) answers = pool.map(self.callDecrypt, self.list_of_objects) """for item in self.list_of_objects: result = item.decrypt(text) answers.append(result)""" for answer in answers: # adds the LC objects together # self.lc = self.lc + answer["lc"] if answer["IsPlaintext?"]: return answer # so vigenere runs ages # and you cant kill threads in a pool # so i just run it last lol] # # Not anymore! #basedcore result = self.callDecrypt(self.vigenere) if result["IsPlaintext?"]: return result + - return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 2=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key: ciphertext = ciphertext.lower() # Do core work group = cipheydists.get_charset("english")["lcase"] expected = cipheydists.get_dist("lcase") + possible_keys = cipheycore.vigenere_crack( + ciphertext, expected, group, mostLikelyKeyLength + ) - possible_keys = cipheycore.vigenere_crack(ciphertext, expected, group, mostLikelyKeyLength) n_keys = len(possible_keys) # Try all the feasible keys for candidate in possible_keys: nice_key = list(candidate.key) # Create a possible key from the letters in allFreqScores: if not self.SILENT_MODE: print("Attempting with key: %s" % nice_key) + decryptedText = cipheycore.vigenere_decrypt( - decryptedText = cipheycore.vigenere_decrypt(ciphertext, candidate.key, group) + ciphertext, candidate.key, group + ) if self.lc.checkLanguage(decryptedText): print(f"AAAAAAAAAAAA {decryptedText}") # Set the hacked ciphertext to the original casing: origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = "".join(origCase) # Check with user to see if the key has been found: return { "</s> ===========changed ref 3=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # offset: 1 <s>origCase) # Check with user to see if the key has been found: return { "lc": self.lc, "IsPlaintext?": True, "Plaintext": decryptedText, "Cipher": "Viginere", "Extra Information": f"The key used is {nice_key}", } # No English-looking decryption found, so return None: return None ===========changed ref 4=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: None, but prints. """ logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") + print(ret["Plaintext"]) - print(ret['Plaintext']) if self.cipher: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey</s>
ciphey.languageCheckerMod.LanguageChecker/LanguageChecker.checkLanguage
Modified
Ciphey~Ciphey
c1303641f65518f0cefb97d1fe10050173fa362a
Can now upload to PyPi with Poetry + Blackened the codebase
<17>:<del> logger.debug( <18>:<add> logger.debug(f"Chi squared failed. Attempting 1000 words") <del> f"Chi squared failed. Attempting 1000 words" <19>:<del> ) <21>:<del> logger.debug( <22>:<add> logger.debug(f"1000 words failed. This is not plaintext") <del> f"1000 words failed. This is not plaintext" <23>:<del> ) <26>:<del> logger.debug( <27>:<add> logger.debug(f"Language check phase 1 complete") <del> f"Language check phase 1 complete" <28>:<del> )
# module: ciphey.languageCheckerMod.LanguageChecker class LanguageChecker: def checkLanguage(self, text: str) -> bool: <0> """Checks to see if the text is in English <1> Uses chisqaured <2> <3> Performs a decryption, but mainly parses the internal data packet and prints useful information. <4> <5> Args: <6> text -> The text we use to perform analysis on <7> <8> Returns: <9> bool -> True if the text is English, False otherwise. <10> <11> """ <12> logger.debug(f"In Language Checker with {text}") <13> if text == "": <14> return False <15> result: bool = self.chi.checkChi(text) <16> if not result: <17> logger.debug( <18> f"Chi squared failed. Attempting 1000 words" <19> ) <20> if not self.dictionary.check1000Words(text): <21> logger.debug( <22> f"1000 words failed. This is not plaintext" <23> ) <24> return False <25> <26> logger.debug( <27> f"Language check phase 1 complete" <28> ) <29> result2: bool = self.dictionary.confirmlanguage(text, "english") <30> logger.debug(f"Result is, dictionary checker, is {result2}") <31> if not result2: <32> logger.debug(f"Language check phase 2 returns false") <33> return False <34> return True <35>
===========unchanged ref 0=========== at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__add__ self.chi = new at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__init__ self.dictionary = dc.dictionaryChecker() self.chi = cs.chiSquared() at: languageCheckerMod.chisquared.chiSquared checkChi(text) at: languageCheckerMod.dictionaryChecker.dictionaryChecker check1000Words(text: str) -> bool confirmlanguage(text: str, language: str) -> True ===========changed ref 0=========== # module: ciphey.languageCheckerMod.chisquared class chiSquared: def __init__(self): self.language = cipheydists.get_dist("twist") self.average = 0.0 self.totalDone = 0.0 self.oldAverage = 0.0 self.mh = mh.mathsHelper() self.highestLanguage = "" self.totalChi = 0.0 self.totalEqual = False self.chisAsaList = [] # these are settings that may impact how the program works overall + self.chiSquaredSignificanceThreshold = 0.001 # The p value that we reject below - self.chiSquaredSignificanceThreshold = 0.001 # The p value that we reject below ===========changed ref 1=========== # module: ciphey.mathsHelper class mathsHelper: @staticmethod def new_sort(new_dict: dict) -> dict: """Uses OrderedDict to sort a dictionary. I think it's faster than my implementation. Args: new_dict -> the dictionary to sort Returns: Returns the dict, but sorted. """ # (f"d is {d}") logger.debug(f"The old dictionary before new_sort() is {new_dict}") + sorted_i = OrderedDict( + sorted(new_dict.items(), key=lambda x: x[1], reverse=True) - sorted_i = OrderedDict(sorted(new_dict.items(), key=lambda x: x[1], reverse=True)) + ) logger.debug(f"The dictionary after new_sort() is {sorted_i}") # sortedI = sort_dictionary(x) return sorted_i ===========changed ref 2=========== # module: ciphey.Decryptor.basicEncryption.basic_parent class BasicParent: + - def decrypt(self, text): self.text = text from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(16) answers = pool.map(self.callDecrypt, self.list_of_objects) """for item in self.list_of_objects: result = item.decrypt(text) answers.append(result)""" for answer in answers: # adds the LC objects together # self.lc = self.lc + answer["lc"] if answer["IsPlaintext?"]: return answer # so vigenere runs ages # and you cant kill threads in a pool # so i just run it last lol] # # Not anymore! #basedcore result = self.callDecrypt(self.vigenere) if result["IsPlaintext?"]: return result + - return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 3=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # Determine the most likely letters for each letter in the key: ciphertext = ciphertext.lower() # Do core work group = cipheydists.get_charset("english")["lcase"] expected = cipheydists.get_dist("lcase") + possible_keys = cipheycore.vigenere_crack( + ciphertext, expected, group, mostLikelyKeyLength + ) - possible_keys = cipheycore.vigenere_crack(ciphertext, expected, group, mostLikelyKeyLength) n_keys = len(possible_keys) # Try all the feasible keys for candidate in possible_keys: nice_key = list(candidate.key) # Create a possible key from the letters in allFreqScores: if not self.SILENT_MODE: print("Attempting with key: %s" % nice_key) + decryptedText = cipheycore.vigenere_decrypt( - decryptedText = cipheycore.vigenere_decrypt(ciphertext, candidate.key, group) + ciphertext, candidate.key, group + ) if self.lc.checkLanguage(decryptedText): print(f"AAAAAAAAAAAA {decryptedText}") # Set the hacked ciphertext to the original casing: origCase = [] for i in range(len(ciphertext)): if ciphertext[i].isupper(): origCase.append(decryptedText[i].upper()) else: origCase.append(decryptedText[i].lower()) decryptedText = "".join(origCase) # Check with user to see if the key has been found: return { "</s> ===========changed ref 4=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # offset: 1 <s>origCase) # Check with user to see if the key has been found: return { "lc": self.lc, "IsPlaintext?": True, "Plaintext": decryptedText, "Cipher": "Viginere", "Extra Information": f"The key used is {nice_key}", } # No English-looking decryption found, so return None: return None
tests.test_main/test_argument_grep_true
Modified
Ciphey~Ciphey
5ce705b5e0c8cfc5fb9b198bb851bc8e3c6dbf18
All tests now succeed
<0>:<add> result = main(text="It was the best of times, it was the worst of times") <del> result = main(text="hello") <2>:<add> assert result == "It was the best of times, it was the worst of times" <del> assert result["Plaintext"] == "hello"
# module: tests.test_main def test_argument_grep_true(): <0> result = main(text="hello") <1> print(result) <2> assert result["Plaintext"] == "hello" <3>
===========changed ref 0=========== + # module: tests.chi + + ===========changed ref 1=========== + # module: tests.integration + + ===========changed ref 2=========== + # module: tests.chi + logger.remove() + ===========changed ref 3=========== + # module: tests.integration + logger.remove() + ===========changed ref 4=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + """ + tests integration between chi squared and dictionary checker + """ + ===========changed ref 5=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_three(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("") + self.assertEqual(result, False) + ===========changed ref 6=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_five(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("#") + self.assertEqual(result, False) + ===========changed ref 7=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_four(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage(".") + self.assertEqual(result, False) + ===========changed ref 8=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_basics_german(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("hallo keine lieben leute nach") + self.assertEqual(result, False) + ===========changed ref 9=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_one(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("HELLO MY NAME IS BRANDON AND I LIKE DOLLAR") + self.assertEqual(result, True) + ===========changed ref 10=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_basics(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage( + "Hello my name is new and this is an example of some english text" + ) + self.assertEqual(result, True) + ===========changed ref 11=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_two(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + self.assertEqual(result, False) + ===========changed ref 12=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_7(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("") + self.assertEqual(result, False) + ===========changed ref 13=========== + # module: tests.chi + class testChi(unittest.TestCase): + def test_chi_english_caps(self): + self.chi = chiSquared() + """ + Tests to see whether a sentene is classified as English or not + """ + result = self.chi.checkChi("Hello My NaME IS BraNdOnnn And I LOVE You!") + self.assertEqual(result, True) + ===========changed ref 14=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_basics_quickbrownfox(self): + """ + This returns true becaue by default chi squared returns true so long as it's less than 10 items it's processed + """ + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("The quick brown fox jumped over the lazy dog") + self.assertEqual(result, True) + ===========changed ref 15=========== + # module: tests.chi + class testChi(unittest.TestCase): + def test_chi_english_yes(self): + """Checks to see if it returns True (it should)""" + self.chi = chiSquared() + """ + Tests to see whether a sentene is classified as English or not + """ + result = self.chi.checkChi( + "Hello my name is Brandon and I'm a top secret message" + ) + self.assertEqual(result, True) + ===========changed ref 16=========== + # module: tests.chi + class testChi(unittest.TestCase): + def tests_english_caesar_false(self): + self.chi = chiSquared() + result = self.chi.checkChi( + "Pm ol ohk hufaopun jvumpkluaphs av zhf, ol dyval pa pu jpwoly, aoha pz, if zv johunpun aol vykly vm aol slaalyz vm aol hswohila, aoha uva h dvyk jvbsk il thkl vba." + ) + + self.assertEqual(result, True) + ===========changed ref 17=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_addition(self): + """ + Makes sure you can add 2 lanuggae objecs together + """ + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("hello my darling") + + lc2 = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("sad as dasr as s") + + temp = lc.getChiScore() + temp2 = lc2.getChiScore() + temp3 = temp + temp2 + lc3 = lc + lc2 + + self.assertAlmostEqual(lc3.getChiScore(), temp3) + ===========changed ref 18=========== + # module: tests.chi + class testChi(unittest.TestCase): + def tests_english_caesar_true(self): + self.chi = chiSquared() + result = self.chi.checkChi( + "Pm ol ohk hufaopun jvumpkluaphs av zhf, ol dyval pa pu jpwoly, aoha pz, if zv johunpun aol vykly vm aol slaalyz vm aol hswohila, aoha uva h dvyk jvbsk il thkl vba." + ) + result = self.chi.checkChi("aolyl pz vusf ylhssf vul dhf mvy aopz av nv kvdu") + result = self.chi.checkChi( + "According to all known laws of aviation, there is no way for a bee to be able to fly. Its wings are simply too small for its fat tiny body." + ) + self.assertEqual(result, True) +
ciphey.__main__/Ciphey.decrypt_normal
Modified
Ciphey~Ciphey
5ce705b5e0c8cfc5fb9b198bb851bc8e3c6dbf18
All tests now succeed
<11>:<add> result = self.lc.checkLanguage(self.text) <add> print(result) <add> if result: <add> print("You inputted plain text!") <add> print(f"Returning {self.text}") <add> return self.text <add>
# module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: <0> """Called by one_level_of_decryption <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> bar -> whether or not to use alive_Bar <6> <7> Returns: <8> None, but prints. <9> <10> """ <11> logger.debug(f"In decrypt_normal") <12> for key, val in self.what_to_choose.items(): <13> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <14> if not isinstance(key, str): <15> key.setProbTable(val) <16> ret: dict = key.decrypt(self.text) <17> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <18> logger.debug( <19> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <20> ) <21> <22> if ret["IsPlaintext?"]: <23> logger.debug(f"Ret is plaintext") <24> print(ret["Plaintext"]) <25> if self.cipher: <26> if ret["Extra Information"] is not None: <27> print( <28> "The cipher used is", <29> ret["Cipher"] + ".", <30> ret["Extra Information"] + ".", <31> ) <32> else: <33> print("The cipher used is " + ret["Cipher"] + ".") <34> return ret <35> <36> logger.debug("No encryption found") <37> print( <38> """No encryption found. Here are some tips to help crack the cipher: <39> * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. </s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: # offset: 1 Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey.__init__ self.lc = lc.LanguageChecker() self.text: str = text self.cipher = cipher self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) at: languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool ===========changed ref 0=========== + # module: tests.chi + + ===========changed ref 1=========== + # module: tests.integration + + ===========changed ref 2=========== + # module: tests.chi + logger.remove() + ===========changed ref 3=========== + # module: tests.integration + logger.remove() + ===========changed ref 4=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + """ + tests integration between chi squared and dictionary checker + """ + ===========changed ref 5=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_three(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("") + self.assertEqual(result, False) + ===========changed ref 6=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_five(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("#") + self.assertEqual(result, False) + ===========changed ref 7=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_four(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage(".") + self.assertEqual(result, False) + ===========changed ref 8=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_basics_german(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("hallo keine lieben leute nach") + self.assertEqual(result, False) + ===========changed ref 9=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_one(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("HELLO MY NAME IS BRANDON AND I LIKE DOLLAR") + self.assertEqual(result, True) + ===========changed ref 10=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_basics(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage( + "Hello my name is new and this is an example of some english text" + ) + self.assertEqual(result, True) + ===========changed ref 11=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_two(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + self.assertEqual(result, False) + ===========changed ref 12=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_7(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("") + self.assertEqual(result, False) + ===========changed ref 13=========== # module: tests.test_main def test_argument_grep_true(): + result = main(text="It was the best of times, it was the worst of times") - result = main(text="hello") print(result) + assert result == "It was the best of times, it was the worst of times" - assert result["Plaintext"] == "hello" ===========changed ref 14=========== + # module: tests.chi + class testChi(unittest.TestCase): + def test_chi_english_caps(self): + self.chi = chiSquared() + """ + Tests to see whether a sentene is classified as English or not + """ + result = self.chi.checkChi("Hello My NaME IS BraNdOnnn And I LOVE You!") + self.assertEqual(result, True) + ===========changed ref 15=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_basics_quickbrownfox(self): + """ + This returns true becaue by default chi squared returns true so long as it's less than 10 items it's processed + """ + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("The quick brown fox jumped over the lazy dog") + self.assertEqual(result, True) + ===========changed ref 16=========== + # module: tests.chi + class testChi(unittest.TestCase): + def test_chi_english_yes(self): + """Checks to see if it returns True (it should)""" + self.chi = chiSquared() + """ + Tests to see whether a sentene is classified as English or not + """ + result = self.chi.checkChi( + "Hello my name is Brandon and I'm a top secret message" + ) + self.assertEqual(result, True) + ===========changed ref 17=========== + # module: tests.chi + class testChi(unittest.TestCase): + def tests_english_caesar_false(self): + self.chi = chiSquared() + result = self.chi.checkChi( + "Pm ol ohk hufaopun jvumpkluaphs av zhf, ol dyval pa pu jpwoly, aoha pz, if zv johunpun aol vykly vm aol slaalyz vm aol hswohila, aoha uva h dvyk jvbsk il thkl vba." + ) + + self.assertEqual(result, True) +
ciphey.__main__/arg_parsing
Modified
Ciphey~Ciphey
5ce705b5e0c8cfc5fb9b198bb851bc8e3c6dbf18
All tests now succeed
# module: ciphey.__main__ def arg_parsing() -> dict: <0> """This function parses arguments. <1> <2> Args: <3> None <4> Returns: <5> A tuple containing the arguments, which is unpacked in main() <6> """ <7> parser = argparse.ArgumentParser( <8> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n <9> Examples: <10> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true <11> """ <12> ) <13> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False) <14> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, <15> # the slower it is)' <16> # required=False) <17> parser.add_argument( <18> "-g", <19> "--greppable", <20> help="Only output the answer, no progress bars or information. Useful for grep", <21> action="store_true", <22> required=False, <23> ) <24> parser.add_argument("-t", "--text", help="Text to decrypt", required=False) <25> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False) <26> parser.add_argument( <27> "-c", <28> "--cipher", <29> help="Do you want information on the cipher used?", <30> action="store_true", <31> required=False, <32> ) <33> # fake argument to stop argparser complaining about no arguments <34> # allows sys.argv to be used <35> # parser.add_argument("-m", action="store_false", default=True, required=False) <36> <37> parser.add_argument( <38> "-d",</s>
===========below chunk 0=========== # module: ciphey.__main__ def arg_parsing() -> dict: # offset: 1 "--debug", help="Activates debug mode", required=False, action="store_true", ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"]: text = args["text"] if args["text"] is None and len(sys.argv) > 1: text = args["rest"][0] if not sys.stdin.isatty(): text = str(sys.stdin.read()) if len(sys.argv) == 1 and text == None: print("No arguments were supplied. Look at the help menu with -h or --help") args["text"] = text if not args["rest"]: args.pop("rest") return args ===========unchanged ref 0=========== at: argparse REMAINDER = '...' ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...) at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: sys argv: List[str] stdin: TextIO at: typing.IO __slots__ = () isatty() -> bool ===========changed ref 0=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: None, but prints. """ + result = self.lc.checkLanguage(self.text) + print(result) + if result: + print("You inputted plain text!") + print(f"Returning {self.text}") + return self.text + logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) if self.cipher: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the</s> ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: # offset: 1 <s> logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========changed ref 2=========== + # module: tests.chi + + ===========changed ref 3=========== + # module: tests.integration + + ===========changed ref 4=========== + # module: tests.chi + logger.remove() + ===========changed ref 5=========== + # module: tests.integration + logger.remove() + ===========changed ref 6=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + """ + tests integration between chi squared and dictionary checker + """ + ===========changed ref 7=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_three(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("") + self.assertEqual(result, False) + ===========changed ref 8=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_five(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("#") + self.assertEqual(result, False) + ===========changed ref 9=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_four(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage(".") + self.assertEqual(result, False) + ===========changed ref 10=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_basics_german(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("hallo keine lieben leute nach") + self.assertEqual(result, False) + ===========changed ref 11=========== + # module: tests.integration + class testIntegration(unittest.TestCase): + def test_integration_unusual_one(self): + lc = LanguageChecker.LanguageChecker() + result = lc.checkLanguage("HELLO MY NAME IS BRANDON AND I LIKE DOLLAR") + self.assertEqual(result, True) +
ciphey.__main__/arg_parsing
Modified
Ciphey~Ciphey
922f8077091cb87cb8f1d017ee24fd59c88ce8d3
Fixed bug in main
# module: ciphey.__main__ def arg_parsing() -> dict: <0> """This function parses arguments. <1> <2> Args: <3> None <4> Returns: <5> A tuple containing the arguments, which is unpacked in main() <6> """ <7> parser = argparse.ArgumentParser( <8> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n <9> Examples: <10> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true <11> """ <12> ) <13> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False) <14> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, <15> # the slower it is)' <16> # required=False) <17> parser.add_argument( <18> "-g", <19> "--greppable", <20> help="Only output the answer, no progress bars or information. Useful for grep", <21> action="store_true", <22> required=False, <23> ) <24> parser.add_argument("-t", "--text", help="Text to decrypt", required=False) <25> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False) <26> parser.add_argument( <27> "-c", <28> "--cipher", <29> help="Do you want information on the cipher used?", <30> action="store_true", <31> required=False, <32> ) <33> # fake argument to stop argparser complaining about no arguments <34> # allows sys.argv to be used <35> # parser.add_argument("-m", action="store_false", default=True, required=False) <36> <37> parser.add_argument( <38> "-d",</s>
===========below chunk 0=========== # module: ciphey.__main__ def arg_parsing() -> dict: # offset: 1 "--debug", help="Activates debug mode", required=False, action="store_true", ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"]: text = args["text"] if args["text"] is None and len(sys.argv) > 1: text = args["rest"][0] if not sys.stdin.isatty(): text = str(sys.stdin.read()) if len(sys.argv) == 1 and text == None: print("No arguments were supplied. Look at the help menu with -h or --help") args["text"] = text if not args["rest"]: args.pop("rest") if args["text"] < 3: print("Your inputted string is less than 3 chars, Ciphey cannot crack it.") return None return args ===========unchanged ref 0=========== at: argparse REMAINDER = '...' ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...) at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: sys argv: List[str] stdin: TextIO at: typing.IO __slots__ = () isatty() -> bool read(n: int=...) -> AnyStr at: typing.MutableMapping pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] pop(key: _KT) -> _VT
tests.test_main/test_argument_grep_true
Modified
Ciphey~Ciphey
dff13e696fb67e4ddd545f3cb8cd5f52b709a53e
Added Nox to github actions
<1>:<del> print(result)
# module: tests.test_main def test_argument_grep_true(): <0> result = main(text="It was the best of times, it was the worst of times") <1> print(result) <2> assert result == "It was the best of times, it was the worst of times" <3>
noxfile/tests
Modified
Ciphey~Ciphey
f926149e45a97d9ec5584bea1833f285cccc80d3
Fixing noxfile
<1>:<add> session.run("pytest") # , "--cov" <del> session.run("pyhon3 -m pytest", "--cov")
# module: noxfile @nox.session(python=["3.8", "3.7", "3.6"]) def tests(session): <0> session.run("poetry", "install", external=True) <1> session.run("pyhon3 -m pytest", "--cov") <2>
noxfile/tests
Modified
Ciphey~Ciphey
f8f0e9e1e851695ec5db8930652674c3a0ff4da2
Added install_with_constraints to nox
<0>:<add> args = session.posargs or ["--cov", "-m", "not e2e"] <add> session.run("poetry", "install", "--no-dev", external=True) <del> session.run("poetry", "install", external=True) <1>:<add> install_with_constraints( <add> session, "coverage[toml]", "pytest", "pytest-cov" <add> ) <add> session.run("pytest", *args) <del> session.run("pytest") # , "--cov"
# module: noxfile + @nox.session(python=["3.8", "3.7"]) - @nox.session(python=["3.8", "3.7", "3.6"]) def tests(session): <0> session.run("poetry", "install", external=True) <1> session.run("pytest") # , "--cov" <2>
===========unchanged ref 0=========== at: noxfile locations = "ciphey/", "tests/"
noxfile/safety
Modified
Ciphey~Ciphey
f8f0e9e1e851695ec5db8930652674c3a0ff4da2
Added install_with_constraints to nox
<10>:<add> install_with_constraints(session, "safety") <del> session.install("safety")
# module: noxfile @nox.session(python="3.8") def safety(session): <0> with tempfile.NamedTemporaryFile() as requirements: <1> session.run( <2> "poetry", <3> "export", <4> "--dev", <5> "--format=requirements.txt", <6> "--without-hashes", <7> f"--output={requirements.name}", <8> external=True, <9> ) <10> session.install("safety") <11> session.run("safety", "check", f"--file={requirements.name}", "--full-report") <12>
===========unchanged ref 0=========== at: noxfile install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None at: typing.IO __slots__ = () ===========changed ref 0=========== # module: noxfile + @nox.session(python=["3.8", "3.7"]) - @nox.session(python=["3.8", "3.7", "3.6"]) def tests(session): + args = session.posargs or ["--cov", "-m", "not e2e"] + session.run("poetry", "install", "--no-dev", external=True) - session.run("poetry", "install", external=True) + install_with_constraints( + session, "coverage[toml]", "pytest", "pytest-cov" + ) + session.run("pytest", *args) - session.run("pytest") # , "--cov"
noxfile/tests
Modified
Ciphey~Ciphey
c07d05f758eb1d417a0b1d5a8c443d1b626a5fb9
nox worsk wtih cov
<0>:<del> args = session.posargs or ["--cov", "-m", "not e2e"] <1>:<add> session.run("poetry", "install", external=True) <del> session.run("poetry", "install", "--no-dev", external=True) <2>:<del> install_with_constraints( <3>:<del> session, "coverage[toml]", "pytest", "pytest-cov" <4>:<del> ) <5>:<del> session.run("pytest", *args) <6>:<add> session.run("pytest", "--cov=ciphey")
# module: noxfile + @nox.session(python=["3.8", "3.7", "3.6"]) - @nox.session(python=["3.8", "3.7"]) def tests(session): <0> args = session.posargs or ["--cov", "-m", "not e2e"] <1> session.run("poetry", "install", "--no-dev", external=True) <2> install_with_constraints( <3> session, "coverage[toml]", "pytest", "pytest-cov" <4> ) <5> session.run("pytest", *args) <6>
===========unchanged ref 0=========== at: noxfile install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None at: typing.IO __slots__ = ()
ciphey.__main__/main
Modified
Ciphey~Ciphey
6501f254d55139ce82a0f376b58f11181d23a2d3
Updates to main
<1>:<add> <add> It gets the arguments in the function definition using locals() <add> if withArgs is True, that means this is being called with command line args <add> so go to arg_parsing() to get those args <add> we then update locals() with the new command line args and remove "withArgs" <add> This function then calls call_encryption(**result) which passes our dict of args <add> to the function as its own arguments using dict unpacking. <add>
# module: ciphey.__main__ def main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict: <0> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <1> Returns: <2> The output of the decryption. <3> """ <4> # testing is if we run pytest <5> result = locals() <6> if withArgs: <7> result.update(arg_parsing()) <8> result.pop("withArgs") <9> <10> output = call_encryption(**result) <11> return output <12>
ciphey.languageCheckerMod.LanguageChecker/LanguageChecker.__add__
Modified
Ciphey~Ciphey
be3ac7713be553c959fc8f4d5beb99c53bae5170
Documentation is now working
<0>:<add> """Adds together 2 languageChecker objects. <del> """Adds together 2 languageChecker objects
# module: ciphey.languageCheckerMod.LanguageChecker class LanguageChecker: def __add__(self, otherLanguageObject): <0> """Adds together 2 languageChecker objects <1> <2> <3> Args: <4> otherLanguageObject -> the other language checker mod <5> <6> Returns: <7> A single languageCheckerObj comprised of 2 <8> <9> """ <10> # sets the added chi squared to be of this one <11> new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj() <12> self.chi = new <13> return self <14>
===========unchanged ref 0=========== at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__add__ self.chi = new at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker.__init__ self.chi = cs.chiSquared() at: languageCheckerMod.chisquared.chiSquared.__init__ self.totalChi = 0.0
ciphey.languageCheckerMod.LanguageChecker/LanguageChecker.checkLanguage
Modified
Ciphey~Ciphey
be3ac7713be553c959fc8f4d5beb99c53bae5170
Documentation is now working
<0>:<add> """Checks to see if the text is in English. <del> """Checks to see if the text is in English <1>:<add>
# module: ciphey.languageCheckerMod.LanguageChecker class LanguageChecker: def checkLanguage(self, text: str) -> bool: <0> """Checks to see if the text is in English <1> Uses chisqaured <2> <3> Performs a decryption, but mainly parses the internal data packet and prints useful information. <4> <5> Args: <6> text -> The text we use to perform analysis on <7> <8> Returns: <9> bool -> True if the text is English, False otherwise. <10> <11> """ <12> logger.debug(f"In Language Checker with {text}") <13> if text == "": <14> return False <15> result: bool = self.chi.checkChi(text) <16> if not result: <17> logger.debug(f"Chi squared failed. Attempting 1000 words") <18> if not self.dictionary.check1000Words(text): <19> logger.debug(f"1000 words failed. This is not plaintext") <20> return False <21> <22> logger.debug(f"Language check phase 1 complete") <23> result2: bool = self.dictionary.confirmlanguage(text, "english") <24> logger.debug(f"Result is, dictionary checker, is {result2}") <25> if not result2: <26> logger.debug(f"Language check phase 2 returns false") <27> return False <28> return True <29>
===========changed ref 0=========== # module: ciphey.languageCheckerMod.LanguageChecker class LanguageChecker: def __add__(self, otherLanguageObject): + """Adds together 2 languageChecker objects. - """Adds together 2 languageChecker objects Args: otherLanguageObject -> the other language checker mod Returns: A single languageCheckerObj comprised of 2 """ # sets the added chi squared to be of this one new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj() self.chi = new return self
ciphey.__main__/Ciphey.decrypt
Modified
Ciphey~Ciphey
be3ac7713be553c959fc8f4d5beb99c53bae5170
Documentation is now working
<9>:<add>
# module: ciphey.__main__ class Ciphey: def decrypt(self): <0> """Performs the decryption of text <1> <2> Creates the probability table, calls one_level_of_decryption <3> <4> Args: <5> None, it uses class variables. <6> <7> Returns: <8> None <9> """ <10> # Read the documentation for more on this function. <11> # checks to see if inputted text is plaintext <12> result = self.lc.checkLanguage(self.text) <13> if result: <14> print("You inputted plain text!") <15> print(f"Returning {self.text}") <16> return self.text <17> self.probability_distribution: dict = self.ai.predictnn(self.text)[0] <18> self.what_to_choose: dict = { <19> self.hash: { <20> "sha1": self.probability_distribution[0], <21> "md5": self.probability_distribution[1], <22> "sha256": self.probability_distribution[2], <23> "sha512": self.probability_distribution[3], <24> }, <25> self.basic: {"caesar": self.probability_distribution[4]}, <26> "plaintext": {"plaintext": self.probability_distribution[5]}, <27> self.encoding: { <28> "reverse": self.probability_distribution[6], <29> "base64": self.probability_distribution[7], <30> "binary": self.probability_distribution[8], <31> "hexadecimal": self.probability_distribution[9], <32> "ascii": self.probability_distribution[10], <33> "morse": self.probability_distribution[11], <34> }, <35> } <36> <37> logger.debug( <38> f"The probability table before 0.1 in __main__ is {self.what_to_choose}" <39> ) <40> <41> # sorts each</s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): # offset: 1 for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. if v < 0.01: self.what_to_choose[key][k] = 0.01 logger.debug( f"The probability table after 0.1 in __main__ is {self.what_to_choose}" ) self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) # Creates and prints the probability table if not self.greppable: logger.debug(f"Self.greppable is {self.greppable}") self.produceprobtable(self.what_to_choose) logger.debug( f"The new probability table after sorting in __main__ is {self.what_to_choose}" ) """ #for each dictionary in the dictionary # sort that dictionary #sort the overall dictionary by the first value of the new dictionary """ output = None if self.level <= 1: output = self.one_level_of_decryption() else: if self.sickomode: print("Sicko mode entered") f = open("decryptionContents.txt", "w") output = self.one_level_of_decryption(file=f) for i in range(0, self.level): # open file and go through each text item pass logger.debug(f"decrypt is outputting {output}") return output ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey one_level_of_decryption() -> None at: ciphey.__main__.Ciphey.__init__ self.mh = mh.mathsHelper() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.sickomode: bool = False self.greppable: bool = grep self.probability_distribution: dict = {} self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.probability_distribution: dict = self.ai.predictnn(self.text)[0] at: ciphey.mathsHelper.mathsHelper sort_prob_table(prob_table: dict) -> dict ===========changed ref 0=========== # module: ciphey.languageCheckerMod.LanguageChecker class LanguageChecker: def __add__(self, otherLanguageObject): + """Adds together 2 languageChecker objects. - """Adds together 2 languageChecker objects Args: otherLanguageObject -> the other language checker mod Returns: A single languageCheckerObj comprised of 2 """ # sets the added chi squared to be of this one new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj() self.chi = new return self ===========changed ref 1=========== # module: ciphey.languageCheckerMod.LanguageChecker class LanguageChecker: def checkLanguage(self, text: str) -> bool: + """Checks to see if the text is in English. - """Checks to see if the text is in English + Uses chisqaured Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: text -> The text we use to perform analysis on Returns: bool -> True if the text is English, False otherwise. """ logger.debug(f"In Language Checker with {text}") if text == "": return False result: bool = self.chi.checkChi(text) if not result: logger.debug(f"Chi squared failed. Attempting 1000 words") if not self.dictionary.check1000Words(text): logger.debug(f"1000 words failed. This is not plaintext") return False logger.debug(f"Language check phase 1 complete") result2: bool = self.dictionary.confirmlanguage(text, "english") logger.debug(f"Result is, dictionary checker, is {result2}") if not result2: logger.debug(f"Language check phase 2 returns false") return False return True
ciphey.__main__/arg_parsing
Modified
Ciphey~Ciphey
be3ac7713be553c959fc8f4d5beb99c53bae5170
Documentation is now working
<6>:<add>
# module: ciphey.__main__ def arg_parsing() -> dict: <0> """This function parses arguments. <1> <2> Args: <3> None <4> Returns: <5> A tuple containing the arguments, which is unpacked in main() <6> """ <7> parser = argparse.ArgumentParser( <8> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n <9> Examples: <10> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true <11> """ <12> ) <13> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False) <14> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, <15> # the slower it is)' <16> # required=False) <17> parser.add_argument( <18> "-g", <19> "--greppable", <20> help="Only output the answer, no progress bars or information. Useful for grep", <21> action="store_true", <22> required=False, <23> ) <24> parser.add_argument("-t", "--text", help="Text to decrypt", required=False) <25> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False) <26> parser.add_argument( <27> "-c", <28> "--cipher", <29> help="Do you want information on the cipher used?", <30> action="store_true", <31> required=False, <32> ) <33> # fake argument to stop argparser complaining about no arguments <34> # allows sys.argv to be used <35> # parser.add_argument("-m", action="store_false", default=True, required=False) <36> <37> parser.add_argument( <38> "-d",</s>
===========below chunk 0=========== # module: ciphey.__main__ def arg_parsing() -> dict: # offset: 1 "--debug", help="Activates debug mode", required=False, action="store_true", ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"]: text = args["text"] if args["text"] is None and len(sys.argv) > 1: text = args["rest"][0] if not sys.stdin.isatty(): text = str(sys.stdin.read()) if len(sys.argv) == 1 and text == None: print("No arguments were supplied. Look at the help menu with -h or --help") args["text"] = text if not args["rest"]: args.pop("rest") if len(args["text"]) < 3: print("Your inputted string is less than 3 chars, Ciphey cannot crack it.") return None return args ===========unchanged ref 0=========== at: argparse REMAINDER = '...' at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: ciphey.__main__ arg_parsing() -> dict at: ciphey.__main__.arg_parsing parser = argparse.ArgumentParser( description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n Examples: python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true """ ) at: sys argv: List[str] stdin: TextIO at: typing.IO __slots__ = () isatty() -> bool read(n: int=...) -> AnyStr at: typing.MutableMapping pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] pop(key: _KT) -> _VT ===========changed ref 0=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): """Performs the decryption of text Creates the probability table, calls one_level_of_decryption Args: None, it uses class variables. Returns: None + """ # Read the documentation for more on this function. # checks to see if inputted text is plaintext result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text self.probability_distribution: dict = self.ai.predictnn(self.text)[0] self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } logger.debug( f"The probability table before 0.1 in __main__ is {self.what_to_choose}" ) # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets</s> ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): # offset: 1 <s>, value in self.what_to_choose.items(): for k, v in value.items(): # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. if v < 0.01: self.what_to_choose[key][k] = 0.01 logger.debug( f"The probability table after 0.1 in __main__ is {self.what_to_choose}" ) self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) # Creates and prints the probability table if not self.greppable: logger.debug(f"Self.greppable is {self.greppable}") self.produceprobtable(self.what_to_choose) logger.debug( f"The new probability table after sorting in __main__ is {self.what_to_choose}" ) """ #for each dictionary in the dictionary # sort that dictionary #sort the overall dictionary by the first value of the new dictionary """ output = None if self.level <= 1: output = self.one_level_of_decryption() else: if self.sickomode: print("Sicko mode entered") f = open("decryptionContents.txt", "w") output = self.one_level_of_decryption(file=f) for i in range(0, self.level): # open file and go through each text item pass logger.debug(f"decrypt is outputting {output}") return output
ciphey.__main__/main
Modified
Ciphey~Ciphey
be3ac7713be553c959fc8f4d5beb99c53bae5170
Documentation is now working
<2>:<add> It gets the arguments in the function definition using locals(). <del> It gets the arguments in the function definition using locals() <3>:<add> if withArgs is True, that means this is being called with command line args. <del> if withArgs is True, that means this is being called with command line args <4>:<add> so go to arg_parsing() to get those args. <del> so go to arg_parsing() to get those args <5>:<add> we then update locals() with the new command line args and remove "withArgs". <del> we then update locals() with the new command line args and remove "withArgs" <6>:<add> This function then calls call_encryption(**result) which passes our dict of args. <del> This function then calls call_encryption(**result) which passes our dict of args <11>:<add>
# module: ciphey.__main__ def main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict: <0> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <1> <2> It gets the arguments in the function definition using locals() <3> if withArgs is True, that means this is being called with command line args <4> so go to arg_parsing() to get those args <5> we then update locals() with the new command line args and remove "withArgs" <6> This function then calls call_encryption(**result) which passes our dict of args <7> to the function as its own arguments using dict unpacking. <8> <9> Returns: <10> The output of the decryption. <11> """ <12> # testing is if we run pytest <13> result = locals() <14> if withArgs: <15> result.update(arg_parsing()) <16> result.pop("withArgs") <17> <18> output = call_encryption(**result) <19> return output <20>
===========unchanged ref 0=========== at: ciphey.__main__ Ciphey(text, grep=False, cipher=False, debug=False) main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict at: ciphey.__main__.Ciphey decrypt() ===========changed ref 0=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): """Performs the decryption of text Creates the probability table, calls one_level_of_decryption Args: None, it uses class variables. Returns: None + """ # Read the documentation for more on this function. # checks to see if inputted text is plaintext result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text self.probability_distribution: dict = self.ai.predictnn(self.text)[0] self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } logger.debug( f"The probability table before 0.1 in __main__ is {self.what_to_choose}" ) # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets</s> ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): # offset: 1 <s>, value in self.what_to_choose.items(): for k, v in value.items(): # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. if v < 0.01: self.what_to_choose[key][k] = 0.01 logger.debug( f"The probability table after 0.1 in __main__ is {self.what_to_choose}" ) self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) # Creates and prints the probability table if not self.greppable: logger.debug(f"Self.greppable is {self.greppable}") self.produceprobtable(self.what_to_choose) logger.debug( f"The new probability table after sorting in __main__ is {self.what_to_choose}" ) """ #for each dictionary in the dictionary # sort that dictionary #sort the overall dictionary by the first value of the new dictionary """ output = None if self.level <= 1: output = self.one_level_of_decryption() else: if self.sickomode: print("Sicko mode entered") f = open("decryptionContents.txt", "w") output = self.one_level_of_decryption(file=f) for i in range(0, self.level): # open file and go through each text item pass logger.debug(f"decrypt is outputting {output}") return output ===========changed ref 2=========== # module: ciphey.__main__ def arg_parsing() -> dict: """This function parses arguments. Args: None Returns: A tuple containing the arguments, which is unpacked in main() + """ parser = argparse.ArgumentParser( description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n Examples: python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true """ ) # parser.add_argument('-f','--file', help='File you want to decrypt', required=False) # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, # the slower it is)' # required=False) parser.add_argument( "-g", "--greppable", help="Only output the answer, no progress bars or information. Useful for grep", action="store_true", required=False, ) parser.add_argument("-t", "--text", help="Text to decrypt", required=False) # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False) parser.add_argument( "-c", "--cipher", help="Do you want information on the cipher used?", action="store_true", required=False, ) # fake argument to stop argparser complaining about no arguments # allows sys.argv to be used # parser.add_argument("-m", action="store_false", default=True, required=False) parser.add_argument( "-d", "--debug", help="Activates debug mode", required=False, action="store_true", )</s> ===========changed ref 3=========== # module: ciphey.__main__ def arg_parsing() -> dict: # offset: 1 <s> help="Activates debug mode", required=False, action="store_true", ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"]: text = args["text"] if args["text"] is None and len(sys.argv) > 1: text = args["rest"][0] if not sys.stdin.isatty(): text = str(sys.stdin.read()) if len(sys.argv) == 1 and text == None: print("No arguments were supplied. Look at the help menu with -h or --help") args["text"] = text if not args["rest"]: args.pop("rest") if len(args["text"]) < 3: print("Your inputted string is less than 3 chars, Ciphey cannot crack it.") return None return args
ciphey.__main__/call_encryption
Modified
Ciphey~Ciphey
be3ac7713be553c959fc8f4d5beb99c53bae5170
Documentation is now working
<1>:<add> <2>:<add> <4>:<add>
# module: ciphey.__main__ def call_encryption( greppable=False, Cipher=False, text=None, debug=False, cipher=False ): <0> """Function to call Encryption, only used because of arguments. <1> Basically, this is what Main used to be before I had to deal with arg parsing <2> Returns: <3> The output of the decryption. <4> """ <5> output = None <6> if text is not None: <7> cipher_obj = Ciphey(text, greppable, Cipher, debug) <8> output = cipher_obj.decrypt() <9> return output <10>
===========changed ref 0=========== # module: ciphey.__main__ def main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict: """Function to deal with arguments. Either calls with args or not. Makes Pytest work. + It gets the arguments in the function definition using locals(). - It gets the arguments in the function definition using locals() + if withArgs is True, that means this is being called with command line args. - if withArgs is True, that means this is being called with command line args + so go to arg_parsing() to get those args. - so go to arg_parsing() to get those args + we then update locals() with the new command line args and remove "withArgs". - 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. - 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. + """ # testing is if we run pytest result = locals() if withArgs: result.update(arg_parsing()) result.pop("withArgs") output = call_encryption(**result) return output ===========changed ref 1=========== # module: ciphey.__main__ def arg_parsing() -> dict: """This function parses arguments. Args: None Returns: A tuple containing the arguments, which is unpacked in main() + """ parser = argparse.ArgumentParser( description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n Examples: python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true """ ) # parser.add_argument('-f','--file', help='File you want to decrypt', required=False) # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, # the slower it is)' # required=False) parser.add_argument( "-g", "--greppable", help="Only output the answer, no progress bars or information. Useful for grep", action="store_true", required=False, ) parser.add_argument("-t", "--text", help="Text to decrypt", required=False) # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False) parser.add_argument( "-c", "--cipher", help="Do you want information on the cipher used?", action="store_true", required=False, ) # fake argument to stop argparser complaining about no arguments # allows sys.argv to be used # parser.add_argument("-m", action="store_false", default=True, required=False) parser.add_argument( "-d", "--debug", help="Activates debug mode", required=False, action="store_true", )</s> ===========changed ref 2=========== # module: ciphey.__main__ def arg_parsing() -> dict: # offset: 1 <s> help="Activates debug mode", required=False, action="store_true", ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"]: text = args["text"] if args["text"] is None and len(sys.argv) > 1: text = args["rest"][0] if not sys.stdin.isatty(): text = str(sys.stdin.read()) if len(sys.argv) == 1 and text == None: print("No arguments were supplied. Look at the help menu with -h or --help") args["text"] = text if not args["rest"]: args.pop("rest") if len(args["text"]) < 3: print("Your inputted string is less than 3 chars, Ciphey cannot crack it.") return None return args ===========changed ref 3=========== # module: ciphey.languageCheckerMod.LanguageChecker class LanguageChecker: def __add__(self, otherLanguageObject): + """Adds together 2 languageChecker objects. - """Adds together 2 languageChecker objects Args: otherLanguageObject -> the other language checker mod Returns: A single languageCheckerObj comprised of 2 """ # sets the added chi squared to be of this one new = otherLanguageObject.getChiSquaredObj() + self.getChiSquaredObj() self.chi = new return self ===========changed ref 4=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): """Performs the decryption of text Creates the probability table, calls one_level_of_decryption Args: None, it uses class variables. Returns: None + """ # Read the documentation for more on this function. # checks to see if inputted text is plaintext result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text self.probability_distribution: dict = self.ai.predictnn(self.text)[0] self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } logger.debug( f"The probability table before 0.1 in __main__ is {self.what_to_choose}" ) # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets</s>
ciphey.Decryptor.Encoding.morsecode/MorseCode.__init__
Modified
Ciphey~Ciphey
e97bfb2c7f925c150996e6508983fc8a3a79c89e
Cleaned up the root folder
<2>:<del> self.MORSE_CODE_DICT = { <3>:<del> "A": ".-", <4>:<del> "B": "-...", <5>:<del> "C": "-.-.", <6>:<del> "D": "-..", <7>:<del> "E": ".", <8>:<del> "F": "..-.", <9>:<del> "G": "--.", <10>:<del> "H": "....", <11>:<del> "I": "..", <12>:<del> "J": ".---", <13>:<del> "K": "-.-", <14>:<del> "L": ".-..", <15>:<del> "M": "--", <16>:<del> "N": "-.", <17>:<del> "O": "---", <18>:<del> "P": ".--.", <19>:<del> "Q": "--.-", <20>:<del> "R": ".-.", <21>:<del> "S": "...", <22>:<del> "T": "-", <23>:<del> "U": "..-", <24>:<del> "V": "...-", <25>:<del> "W": ".--", <26>:<del> "X": "-..-", <27>:<del> "Y": "-.--", <28>:<del> "Z": "--..", <29>:<del> "?": "..--..", <30>:<del> ".": ".-.-.-", <31>:<del> " ": "/", <32>:<del> "0": "-----", <33>:<del> "1": ".----", <34>:<del> "2": "..---", <35>:<del> "3": "...--", <36>:<del> "4": "....-", <37>:<del> "5": ".....", <38>:<del> "6": "-....", <39>:<del> "7": "--...", <40>:<del> "8": "---..", <41>:<del> "9": "----.", <42>:<del> " ": "\n", <43>:<del> } <44>:<del> <45>:<add> self.MORSE_CODE_DICT = dict(cipheydists.get_charset("morse"))
# module: ciphey.Decryptor.Encoding.morsecode - class MorseCode: def __init__(self, lc): <0> self.lc = lc <1> self.ALLOWED = [".", "-", " ", "/", "\n"] <2> self.MORSE_CODE_DICT = { <3> "A": ".-", <4> "B": "-...", <5> "C": "-.-.", <6> "D": "-..", <7> "E": ".", <8> "F": "..-.", <9> "G": "--.", <10> "H": "....", <11> "I": "..", <12> "J": ".---", <13> "K": "-.-", <14> "L": ".-..", <15> "M": "--", <16> "N": "-.", <17> "O": "---", <18> "P": ".--.", <19> "Q": "--.-", <20> "R": ".-.", <21> "S": "...", <22> "T": "-", <23> "U": "..-", <24> "V": "...-", <25> "W": ".--", <26> "X": "-..-", <27> "Y": "-.--", <28> "Z": "--..", <29> "?": "..--..", <30> ".": ".-.-.-", <31> " ": "/", <32> "0": "-----", <33> "1": ".----", <34> "2": "..---", <35> "3": "...--", <36> "4": "....-", <37> "5": ".....", <38> "6": "-....", <39> "7": "--...", <40> "8": "---..", <41> "9": "----.", <42> " ": "\n", <43> } <44> <45> self.MORSE</s>
===========below chunk 0=========== # module: ciphey.Decryptor.Encoding.morsecode - class MorseCode: def __init__(self, lc): # offset: 1
noxfile/coverage
Modified
Ciphey~Ciphey
ba8e279efa9dca476bac843560aecafa926970cb
I hope this fixes CI
<2>:<add> session.run("pip3", "install", "cipheydists")
# module: noxfile @nox.session(python="3.8") def coverage(session: Session) -> None: <0> """Upload coverage data.""" <1> install_with_constraints(session, "coverage[toml]", "codecov") <2> session.run("coverage", "xml", "--fail-under=0") <3> session.run("codecov", *session.posargs) <4>
===========unchanged ref 0=========== at: noxfile install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None
noxfile/tests
Modified
Ciphey~Ciphey
ba8e279efa9dca476bac843560aecafa926970cb
I hope this fixes CI
<0>:<add> session.run("pip3", "install", "cipheydists") <1>:<add> session.run("poetry", "run", "pytest", "--cov=ciphey") <del> session.run("pytest", "--cov=ciphey")
# module: noxfile # python=["3.8", "3.7", "3.6"]) @nox.session(python="3.8") def tests(session): <0> session.run("poetry", "install", external=True) <1> session.run("pytest", "--cov=ciphey") <2>
===========changed ref 0=========== # module: noxfile @nox.session(python="3.8") def coverage(session: Session) -> None: """Upload coverage data.""" install_with_constraints(session, "coverage[toml]", "codecov") + session.run("pip3", "install", "cipheydists") session.run("coverage", "xml", "--fail-under=0") session.run("codecov", *session.posargs)
ciphey.Decryptor.basicEncryption.vigenere/Vigenere.attemptHackWithKeyLength
Modified
Ciphey~Ciphey
3f03abbf270e4e68b8985227f308f66b3d699b79
removed useless print statement
<23>:<del> print(f"AAAAAAAAAAAA {decryptedText}")
# module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): <0> # Determine the most likely letters for each letter in the key: <1> ciphertext = ciphertext.lower() <2> <3> # Do core work <4> group = cipheydists.get_charset("english")["lcase"] <5> expected = cipheydists.get_dist("lcase") <6> possible_keys = cipheycore.vigenere_crack( <7> ciphertext, expected, group, mostLikelyKeyLength <8> ) <9> n_keys = len(possible_keys) <10> <11> # Try all the feasible keys <12> for candidate in possible_keys: <13> nice_key = list(candidate.key) <14> # Create a possible key from the letters in allFreqScores: <15> if not self.SILENT_MODE: <16> print("Attempting with key: %s" % nice_key) <17> <18> decryptedText = cipheycore.vigenere_decrypt( <19> ciphertext, candidate.key, group <20> ) <21> <22> if self.lc.checkLanguage(decryptedText): <23> print(f"AAAAAAAAAAAA {decryptedText}") <24> # Set the hacked ciphertext to the original casing: <25> origCase = [] <26> for i in range(len(ciphertext)): <27> if ciphertext[i].isupper(): <28> origCase.append(decryptedText[i].upper()) <29> else: <30> origCase.append(decryptedText[i].lower()) <31> decryptedText = "".join(origCase) <32> <33> # Check with user to see if the key has been found: <34> return { <35> "lc": self.lc, <36> "IsPlaintext?": True, <37> "Plaintext": decryptedText, <38> </s>
===========below chunk 0=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: def attemptHackWithKeyLength(self, ciphertext, mostLikelyKeyLength): # offset: 1 "Extra Information": f"The key used is {nice_key}", } # No English-looking decryption found, so return None: return None ===========unchanged ref 0=========== at: ciphey.Decryptor.basicEncryption.vigenere.Vigenere.__init__ self.SILENT_MODE = True # If set to True, program doesn't print anything. self.lc = lc at: languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool
ciphey.Decryptor.Encoding.bases/Bases.base64
Modified
Ciphey~Ciphey
123a83efcd6aef33fcc361fdfce6f4ea3c872178
Fixed encodings
<7>:<add> logger.trace("Attempting base64") <del> logger.debug(f"Attempting base64") <14>:<add> return None <del> None <16>:<add> return None <del> None <18>:<add> return None <del> None <20>:<add> if result is not None and self.lc.checkLanguage(result): <del> if self.lc.checkLanguage(result) and result != "None":
# module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text): <0> """Bases decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base64 <6> """ <7> logger.debug(f"Attempting base64") <8> result = None <9> try: <10> result = base64.b64decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> None <15> except binascii.Error as e: <16> None <17> except ValueError: <18> None <19> <20> if self.lc.checkLanguage(result) and result != "None": <21> logger.debug(f"Bases successful, returning {result}") <22> return self.goodRet(result, cipher="Bases") <23>
===========unchanged ref 0=========== at: base64 b64decode(s: _decodable, altchars: Optional[bytes]=..., validate: bool=...) -> bytes at: binascii Error(*args: object) at: ciphey.Decryptor.Encoding.bases.Bases goodRet(result, cipher) at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool
ciphey.Decryptor.Encoding.bases/Bases.base32
Modified
Ciphey~Ciphey
123a83efcd6aef33fcc361fdfce6f4ea3c872178
Fixed encodings
<7>:<add> logger.trace("Attempting base32") <del> logger.debug("attempting base32") <14>:<add> return None <del> None <16>:<add> return None <del> None <18>:<add> return None <del> None <20>:<add> if result is not None and self.lc.checkLanguage(result): <del> if self.lc.checkLanguage(result) and result != "None":
# module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text): <0> """Base32 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base32 <6> """ <7> logger.debug("attempting base32") <8> result = None <9> try: <10> result = base64.b32decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> None <15> except binascii.Error as e: <16> None <17> except ValueError: <18> None <19> <20> if self.lc.checkLanguage(result) and result != "None": <21> logger.debug(f"base32 successful, {result}") <22> return self.goodRet(result, cipher="Base32") <23>
===========unchanged ref 0=========== at: base64 b32decode(s: _decodable, casefold: bool=..., map01: Optional[bytes]=...) -> bytes at: binascii Error(*args: object) at: ciphey.Decryptor.Encoding.bases.Bases goodRet(result, cipher) at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text): """Bases decode args: text -> text to decode returns: the text decoded as base64 """ + logger.trace("Attempting base64") - logger.debug(f"Attempting base64") result = None try: result = base64.b64decode(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: + return None - None except binascii.Error as e: + return None - None except ValueError: + return None - None + if result is not None and self.lc.checkLanguage(result): - if self.lc.checkLanguage(result) and result != "None": logger.debug(f"Bases successful, returning {result}") return self.goodRet(result, cipher="Bases")
ciphey.Decryptor.Encoding.bases/Bases.base16
Modified
Ciphey~Ciphey
123a83efcd6aef33fcc361fdfce6f4ea3c872178
Fixed encodings
<7>:<add> logger.trace("Attempting base32") <del> logger.debug("attempting base32") <14>:<add> return None <del> None <16>:<add> return None <del> None <18>:<add> return None <del> None <19>:<add> if result is not None and self.lc.checkLanguage(result): <del> if self.lc.checkLanguage(result) and result != "None":
# module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text): <0> """Base16 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base16 <6> """ <7> logger.debug("attempting base32") <8> result = None <9> try: <10> result = base64.b16decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> None <15> except binascii.Error as e: <16> None <17> except ValueError: <18> None <19> if self.lc.checkLanguage(result) and result != "None": <20> logger.debug(f"Base16 successful, {result}") <21> return self.goodRet(result, cipher="Base16") <22>
===========unchanged ref 0=========== at: base64 b16decode(s: _decodable, casefold: bool=...) -> bytes at: binascii Error(*args: object) at: ciphey.Decryptor.Encoding.bases.Bases goodRet(result, cipher) at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ + logger.trace("Attempting base32") - logger.debug("attempting base32") result = None try: result = base64.b32decode(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: + return None - None except binascii.Error as e: + return None - None except ValueError: + return None - None + if result is not None and self.lc.checkLanguage(result): - if self.lc.checkLanguage(result) and result != "None": logger.debug(f"base32 successful, {result}") return self.goodRet(result, cipher="Base32") ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text): """Bases decode args: text -> text to decode returns: the text decoded as base64 """ + logger.trace("Attempting base64") - logger.debug(f"Attempting base64") result = None try: result = base64.b64decode(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: + return None - None except binascii.Error as e: + return None - None except ValueError: + return None - None + if result is not None and self.lc.checkLanguage(result): - if self.lc.checkLanguage(result) and result != "None": logger.debug(f"Bases successful, returning {result}") return self.goodRet(result, cipher="Bases")
ciphey.Decryptor.Encoding.bases/Bases.base85
Modified
Ciphey~Ciphey
123a83efcd6aef33fcc361fdfce6f4ea3c872178
Fixed encodings
<7>:<add> logger.trace("Attempting base85") <del> logger.debug("Attempting base85") <14>:<add> return None <del> None <16>:<add> return None <del> None <18>:<add> return None <del> None <20>:<add> if result is not None and self.lc.checkLanguage(result): <del> if self.lc.checkLanguage(result) and result != "None":
# module: ciphey.Decryptor.Encoding.bases class Bases: def base85(self, text): <0> """Base85 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base85 <6> """ <7> logger.debug("Attempting base85") <8> result = None <9> try: <10> result = base64.b85decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> None <15> except binascii.Error as e: <16> None <17> except ValueError: <18> None <19> <20> if self.lc.checkLanguage(result) and result != "None": <21> logger.debug(f"Base85 successful, {result}") <22> return self.goodRet(result, cipher="Base85") <23>
===========unchanged ref 0=========== at: base64 b85decode(b: _decodable) -> bytes at: binascii Error(*args: object) at: ciphey.Decryptor.Encoding.bases.Bases goodRet(result, cipher) at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text): """Base16 decode args: text -> text to decode returns: the text decoded as base16 """ + logger.trace("Attempting base32") - logger.debug("attempting base32") result = None try: result = base64.b16decode(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: + return None - None except binascii.Error as e: + return None - None except ValueError: + return None - None + if result is not None and self.lc.checkLanguage(result): - if self.lc.checkLanguage(result) and result != "None": logger.debug(f"Base16 successful, {result}") return self.goodRet(result, cipher="Base16") ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ + logger.trace("Attempting base32") - logger.debug("attempting base32") result = None try: result = base64.b32decode(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: + return None - None except binascii.Error as e: + return None - None except ValueError: + return None - None + if result is not None and self.lc.checkLanguage(result): - if self.lc.checkLanguage(result) and result != "None": logger.debug(f"base32 successful, {result}") return self.goodRet(result, cipher="Base32") ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text): """Bases decode args: text -> text to decode returns: the text decoded as base64 """ + logger.trace("Attempting base64") - logger.debug(f"Attempting base64") result = None try: result = base64.b64decode(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: + return None - None except binascii.Error as e: + return None - None except ValueError: + return None - None + if result is not None and self.lc.checkLanguage(result): - if self.lc.checkLanguage(result) and result != "None": logger.debug(f"Bases successful, returning {result}") return self.goodRet(result, cipher="Bases")
ciphey.Decryptor.Encoding.bases/Bases.decrypt
Modified
Ciphey~Ciphey
e5a09600bbc2a70b4138b82d08890cc201eef8fb
Refactored encodings
<0>:<add> logger.debug("Attempting base decoding") <del> logger.debug("Attempting base decoding") <1>:<del> <2>:<del> bases = [ <3>:<del> self.base32(text), <4>:<del> self.base16(text), <5>:<del> self.base64(text), <6>:<del> ] <7>:<del> for answer in bases: <8>:<del> try: <9>:<del> if answer["IsPlaintext?"]: <10>:<del> # good answer <11>:<del> logger.debug(f"Returning true for {answer}") <12>:<del> return answer <13>:<del> except TypeError: <14>:<del> continue <15>:<del> # Base85 <16>:<del> # if nothing works, it has failed. <17>:<del> return self.badRet()
# module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def decrypt(self, text: str): - def decrypt(self, text): <0> logger.debug("Attempting base decoding") <1> <2> bases = [ <3> self.base32(text), <4> self.base16(text), <5> self.base64(text), <6> ] <7> for answer in bases: <8> try: <9> if answer["IsPlaintext?"]: <10> # good answer <11> logger.debug(f"Returning true for {answer}") <12> return answer <13> except TypeError: <14> continue <15> # Base85 <16> # if nothing works, it has failed. <17> return self.badRet() <18>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.bases.Bases base64(text: str) base64(self, text: str) base32(self, text: str) base32(text: str) base16(text: str) base16(self, text: str)
ciphey.Decryptor.Encoding.bases/Bases.base64
Modified
Ciphey~Ciphey
e5a09600bbc2a70b4138b82d08890cc201eef8fb
Refactored encodings
<0>:<add> """Base64 decode <del> """Bases decode <1>:<del> <2>:<del> args: <3>:<del> text -> text to decode <4>:<del> returns: <5>:<del> the text decoded as base64 <6>:<del> """ <7>:<del> logger.trace("Attempting base64") <8>:<del> result = None <9>:<del> try: <10>:<del> result = base64.b64decode(text) <11>:<del> # yeet turning b strings into normal stringy bois <12>:<del> result = result.decode("utf-8") <13>:<del> except UnicodeDecodeError as e: <14>:<del> return None <15>:<del> except binascii.Error as e: <16>:<del> return None <17>:<del> except ValueError: <18>:<del> return None <19>:<del> <20>:<del> if result is not None and self.lc.checkLanguage(result): <21>:<del> logger.debug(f"Bases successful, returning {result}") <22>:<del> return self.goodRet(result, cipher="Bases")
# module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base64(self, text: str): - def base64(self, text): <0> """Bases decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base64 <6> """ <7> logger.trace("Attempting base64") <8> result = None <9> try: <10> result = base64.b64decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> return None <15> except binascii.Error as e: <16> return None <17> except ValueError: <18> return None <19> <20> if result is not None and self.lc.checkLanguage(result): <21> logger.debug(f"Bases successful, returning {result}") <22> return self.goodRet(result, cipher="Bases") <23>
===========unchanged ref 0=========== at: binascii Error(*args: object) at: ciphey.Decryptor.Encoding.bases.Bases goodRet(result, cipher) goodRet(self, result, cipher) badRet(self) badRet() at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool at: typing Callable = _CallableType(collections.abc.Callable, 2) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def decrypt(self, text: str): - def decrypt(self, text): + logger.debug("Attempting base decoding") - logger.debug("Attempting base decoding") - - bases = [ - self.base32(text), - self.base16(text), - self.base64(text), - ] - for answer in bases: - try: - if answer["IsPlaintext?"]: - # good answer - logger.debug(f"Returning true for {answer}") - return answer - except TypeError: - continue - # Base85 - # if nothing works, it has failed. - return self.badRet()
ciphey.Decryptor.Encoding.bases/Bases.base32
Modified
Ciphey~Ciphey
e5a09600bbc2a70b4138b82d08890cc201eef8fb
Refactored encodings
<0>:<add> """Base32 decode <del> """Base32 decode <1>:<del> <2>:<del> args: <3>:<del> text -> text to decode <4>:<del> returns: <5>:<del> the text decoded as base32 <6>:<del> """ <7>:<del> logger.trace("Attempting base32") <8>:<del> result = None <9>:<del> try: <10>:<del> result = base64.b32decode(text) <11>:<del> # yeet turning b strings into normal stringy bois <12>:<del> result = result.decode("utf-8") <13>:<del> except UnicodeDecodeError as e: <14>:<del> return None <15>:<del> except binascii.Error as e: <16>:<del> return None <17>:<del> except ValueError: <18>:<del> return None <19>:<del> <20>:<del> if result is not None and self.lc.checkLanguage(result): <21>:<del> logger.debug(f"base32 successful, {result}") <22>:<del> return self.goodRet(result, cipher="Base32")
# module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base32(self, text: str): - def base32(self, text): <0> """Base32 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base32 <6> """ <7> logger.trace("Attempting base32") <8> result = None <9> try: <10> result = base64.b32decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> return None <15> except binascii.Error as e: <16> return None <17> except ValueError: <18> return None <19> <20> if result is not None and self.lc.checkLanguage(result): <21> logger.debug(f"base32 successful, {result}") <22> return self.goodRet(result, cipher="Base32") <23>
===========unchanged ref 0=========== at: base64 b64decode(s: _decodable, altchars: Optional[bytes]=..., validate: bool=...) -> bytes at: ciphey.Decryptor.Encoding.bases.Bases _dispatch(self, decoder: Callable[[str], bytes], text: str) _dispatch(decoder: Callable[[str], bytes], text: str) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str): + logger.trace("Attempting base64") + result = None + try: + result = decoder(text) + # yeet turning b strings into normal stringy bois + result = result.decode("utf-8") + except UnicodeDecodeError as e: + result = None + except binascii.Error as e: + result = None + except ValueError: + result = None + + if result is not None and self.lc.checkLanguage(result): + logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher="Bases") + ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def decrypt(self, text: str): - def decrypt(self, text): + logger.debug("Attempting base decoding") - logger.debug("Attempting base decoding") - - bases = [ - self.base32(text), - self.base16(text), - self.base64(text), - ] - for answer in bases: - try: - if answer["IsPlaintext?"]: - # good answer - logger.debug(f"Returning true for {answer}") - return answer - except TypeError: - continue - # Base85 - # if nothing works, it has failed. - return self.badRet() ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base64(self, text: str): - def base64(self, text): + """Base64 decode - """Bases decode - - args: - text -> text to decode - returns: - the text decoded as base64 - """ - logger.trace("Attempting base64") - result = None - try: - result = base64.b64decode(text) - # yeet turning b strings into normal stringy bois - result = result.decode("utf-8") - except UnicodeDecodeError as e: - return None - except binascii.Error as e: - return None - except ValueError: - return None - - if result is not None and self.lc.checkLanguage(result): - logger.debug(f"Bases successful, returning {result}") - return self.goodRet(result, cipher="Bases")
ciphey.Decryptor.Encoding.bases/Bases.base16
Modified
Ciphey~Ciphey
e5a09600bbc2a70b4138b82d08890cc201eef8fb
Refactored encodings
<0>:<add> """Base16 decode <del> """Base16 decode <1>:<del> <2>:<del> args: <3>:<del> text -> text to decode <4>:<del> returns: <5>:<del> the text decoded as base16 <6>:<del> """ <7>:<del> logger.trace("Attempting base32") <8>:<del> result = None <9>:<del> try: <10>:<del> result = base64.b16decode(text) <11>:<del> # yeet turning b strings into normal stringy bois <12>:<del> result = result.decode("utf-8") <13>:<del> except UnicodeDecodeError as e: <14>:<del> return None <15>:<del> except binascii.Error as e: <16>:<del> return None <17>:<del> except ValueError: <18>:<del> return None <19>:<del> if result is not None and self.lc.checkLanguage(result): <20>:<del> logger.debug(f"Base16 successful, {result}") <21>:<del> return self.goodRet(result, cipher="Base16")
# module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base16(self, text: str): - def base16(self, text): <0> """Base16 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base16 <6> """ <7> logger.trace("Attempting base32") <8> result = None <9> try: <10> result = base64.b16decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> return None <15> except binascii.Error as e: <16> return None <17> except ValueError: <18> return None <19> if result is not None and self.lc.checkLanguage(result): <20> logger.debug(f"Base16 successful, {result}") <21> return self.goodRet(result, cipher="Base16") <22>
===========unchanged ref 0=========== at: base64 b16decode(s: _decodable, casefold: bool=...) -> bytes b85decode(b: _decodable) -> bytes at: ciphey.Decryptor.Encoding.bases.Bases _dispatch(self, decoder: Callable[[str], bytes], text: str) _dispatch(decoder: Callable[[str], bytes], text: str) at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str): + logger.trace("Attempting base64") + result = None + try: + result = decoder(text) + # yeet turning b strings into normal stringy bois + result = result.decode("utf-8") + except UnicodeDecodeError as e: + result = None + except binascii.Error as e: + result = None + except ValueError: + result = None + + if result is not None and self.lc.checkLanguage(result): + logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher="Bases") + ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def decrypt(self, text: str): - def decrypt(self, text): + logger.debug("Attempting base decoding") - logger.debug("Attempting base decoding") - - bases = [ - self.base32(text), - self.base16(text), - self.base64(text), - ] - for answer in bases: - try: - if answer["IsPlaintext?"]: - # good answer - logger.debug(f"Returning true for {answer}") - return answer - except TypeError: - continue - # Base85 - # if nothing works, it has failed. - return self.badRet() ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base32(self, text: str): - def base32(self, text): + """Base32 decode - """Base32 decode - - args: - text -> text to decode - returns: - the text decoded as base32 - """ - logger.trace("Attempting base32") - result = None - try: - result = base64.b32decode(text) - # yeet turning b strings into normal stringy bois - result = result.decode("utf-8") - except UnicodeDecodeError as e: - return None - except binascii.Error as e: - return None - except ValueError: - return None - - if result is not None and self.lc.checkLanguage(result): - logger.debug(f"base32 successful, {result}") - return self.goodRet(result, cipher="Base32") ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base64(self, text: str): - def base64(self, text): + """Base64 decode - """Bases decode - - args: - text -> text to decode - returns: - the text decoded as base64 - """ - logger.trace("Attempting base64") - result = None - try: - result = base64.b64decode(text) - # yeet turning b strings into normal stringy bois - result = result.decode("utf-8") - except UnicodeDecodeError as e: - return None - except binascii.Error as e: - return None - except ValueError: - return None - - if result is not None and self.lc.checkLanguage(result): - logger.debug(f"Bases successful, returning {result}") - return self.goodRet(result, cipher="Bases")
ciphey.Decryptor.Encoding.bases/Bases.base85
Modified
Ciphey~Ciphey
e5a09600bbc2a70b4138b82d08890cc201eef8fb
Refactored encodings
<0>:<add> """Base85 decode <del> """Base85 decode <1>:<del> <2>:<del> args: <3>:<del> text -> text to decode <4>:<del> returns: <5>:<del> the text decoded as base85 <6>:<del> """ <7>:<del> logger.trace("Attempting base85") <8>:<del> result = None <9>:<del> try: <10>:<del> result = base64.b85decode(text) <11>:<del> # yeet turning b strings into normal stringy bois <12>:<del> result = result.decode("utf-8") <13>:<del> except UnicodeDecodeError as e: <14>:<del> return None <15>:<del> except binascii.Error as e: <16>:<del> return None <17>:<del> except ValueError: <18>:<del> return None <19>:<del> <20>:<del> if result is not None and self.lc.checkLanguage(result): <21>:<del> logger.debug(f"Base85 successful, {result}") <22>:<del> return self.goodRet(result, cipher="Base85")
# module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base85(self, text: str): - def base85(self, text): <0> """Base85 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base85 <6> """ <7> logger.trace("Attempting base85") <8> result = None <9> try: <10> result = base64.b85decode(text) <11> # yeet turning b strings into normal stringy bois <12> result = result.decode("utf-8") <13> except UnicodeDecodeError as e: <14> return None <15> except binascii.Error as e: <16> return None <17> except ValueError: <18> return None <19> <20> if result is not None and self.lc.checkLanguage(result): <21> logger.debug(f"Base85 successful, {result}") <22> return self.goodRet(result, cipher="Base85") <23>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str): + logger.trace("Attempting base64") + result = None + try: + result = decoder(text) + # yeet turning b strings into normal stringy bois + result = result.decode("utf-8") + except UnicodeDecodeError as e: + result = None + except binascii.Error as e: + result = None + except ValueError: + result = None + + if result is not None and self.lc.checkLanguage(result): + logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher="Bases") + ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base16(self, text: str): - def base16(self, text): + """Base16 decode - """Base16 decode - - args: - text -> text to decode - returns: - the text decoded as base16 - """ - logger.trace("Attempting base32") - result = None - try: - result = base64.b16decode(text) - # yeet turning b strings into normal stringy bois - result = result.decode("utf-8") - except UnicodeDecodeError as e: - return None - except binascii.Error as e: - return None - except ValueError: - return None - if result is not None and self.lc.checkLanguage(result): - logger.debug(f"Base16 successful, {result}") - return self.goodRet(result, cipher="Base16") ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def decrypt(self, text: str): - def decrypt(self, text): + logger.debug("Attempting base decoding") - logger.debug("Attempting base decoding") - - bases = [ - self.base32(text), - self.base16(text), - self.base64(text), - ] - for answer in bases: - try: - if answer["IsPlaintext?"]: - # good answer - logger.debug(f"Returning true for {answer}") - return answer - except TypeError: - continue - # Base85 - # if nothing works, it has failed. - return self.badRet() ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base32(self, text: str): - def base32(self, text): + """Base32 decode - """Base32 decode - - args: - text -> text to decode - returns: - the text decoded as base32 - """ - logger.trace("Attempting base32") - result = None - try: - result = base64.b32decode(text) - # yeet turning b strings into normal stringy bois - result = result.decode("utf-8") - except UnicodeDecodeError as e: - return None - except binascii.Error as e: - return None - except ValueError: - return None - - if result is not None and self.lc.checkLanguage(result): - logger.debug(f"base32 successful, {result}") - return self.goodRet(result, cipher="Base32") ===========changed ref 4=========== # module: ciphey.Decryptor.Encoding.bases - - class Bases: - + def base64(self, text: str): - def base64(self, text): + """Base64 decode - """Bases decode - - args: - text -> text to decode - returns: - the text decoded as base64 - """ - logger.trace("Attempting base64") - result = None - try: - result = base64.b64decode(text) - # yeet turning b strings into normal stringy bois - result = result.decode("utf-8") - except UnicodeDecodeError as e: - return None - except binascii.Error as e: - return None - except ValueError: - return None - - if result is not None and self.lc.checkLanguage(result): - logger.debug(f"Bases successful, returning {result}") - return self.goodRet(result, cipher="Bases")
ciphey.Decryptor.Encoding.bases/Bases._dispatch
Modified
Ciphey~Ciphey
34644d7ba20a0a05f5f3243485f370e749fdc4c3
Made encodings more verbose
<7>:<add> logger.trace("Bad unicode") <9>:<add> logger.trace("binascii error") <11>:<add> logger.trace("Failed to decode base") <16>:<add> else: <add> return self.badRet()
# module: ciphey.Decryptor.Encoding.bases class Bases: def _dispatch(self, decoder: Callable[[str], bytes], text: str): <0> logger.trace("Attempting base64") <1> result = None <2> try: <3> result = decoder(text) <4> # yeet turning b strings into normal stringy bois <5> result = result.decode("utf-8") <6> except UnicodeDecodeError as e: <7> result = None <8> except binascii.Error as e: <9> result = None <10> except ValueError: <11> result = None <12> <13> if result is not None and self.lc.checkLanguage(result): <14> logger.debug(f"Bases successful, returning {result}") <15> return self.goodRet(result, cipher="Bases") <16>
===========unchanged ref 0=========== at: binascii Error(*args: object) at: typing Callable = _CallableType(collections.abc.Callable, 2)
ciphey.__main__/Ciphey.decrypt_normal
Modified
Ciphey~Ciphey
1559bff63dccf143477872653cda2289bfb4d6c7
Removed annoying debug
<12>:<del> print(result)
# module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: <0> """Called by one_level_of_decryption <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> bar -> whether or not to use alive_Bar <6> <7> Returns: <8> None, but prints. <9> <10> """ <11> result = self.lc.checkLanguage(self.text) <12> print(result) <13> if result: <14> print("You inputted plain text!") <15> print(f"Returning {self.text}") <16> return self.text <17> <18> logger.debug(f"In decrypt_normal") <19> for key, val in self.what_to_choose.items(): <20> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <21> if not isinstance(key, str): <22> key.setProbTable(val) <23> ret: dict = key.decrypt(self.text) <24> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <25> logger.debug( <26> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <27> ) <28> <29> if ret["IsPlaintext?"]: <30> logger.debug(f"Ret is plaintext") <31> print(ret["Plaintext"]) <32> if self.cipher: <33> if ret["Extra Information"] is not None: <34> print( <35> "The cipher used is", <36> ret["Cipher"] + ".", <37> ret["Extra Information"] + ".", <38> ) <39> else: <40> print("The cipher used is " + ret["Cipher"] + ".") <41> return ret</s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: # offset: 1 logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey.__init__ self.lc = lc.LanguageChecker() self.text: str = text self.cipher = cipher self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) at: ciphey.languageCheckerMod.LanguageChecker.LanguageChecker checkLanguage(text: str) -> bool
ciphey.Decryptor.Encoding.bases/Bases.base32
Modified
Ciphey~Ciphey
d5f7c8dc0b7103bf50a57ce01b0d5df4ae1c0d10
Fixed oopsie
<8>:<add> return self._dispatch(base64.b32decode, text) <del> return self._dispatch(base64.b64decode, text)
# module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): <0> """Base32 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base32 <6> """ <7> logger.trace("Attempting base32") <8> return self._dispatch(base64.b64decode, text) <9>
===========unchanged ref 0=========== at: base64 b32decode(s: _decodable, casefold: bool=..., map01: Optional[bytes]=...) -> bytes at: ciphey.Decryptor.Encoding.bases.Bases _dispatch(decoder: Callable[[str], bytes], text: str)
ciphey.__main__/Ciphey.__init__
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<0>:<del> if not debug: <1>:<add> logger.remove() <del> logger.remove() <2>:<add> logger.configure() <add> logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) <add> logger.opt(colors=True) <add> logger.trace(f"""Finished argument object is {config}""") <add> logger.debug(f"""Debug level set to {config["debug"]}""") <4>:<add> self.lc = config["checker"](config) <del> self.lc = lc.LanguageChecker() <7>:<add> self.text: str = config["ctext"] <del> self.text: str = text <8>:<del> logger.debug(f"The inputted text at __main__ is {self.text}") <13>:<del> self.sickomode: bool = False <14>:<add> self.greppable: bool = config["grep"] <del> self.greppable: bool = grep <15>:<add> self.cipher_info = config["info"] <del> self.cipher = cipher
# module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): <0> if not debug: <1> logger.remove() <2> # general purpose modules <3> self.ai = NeuralNetwork() <4> self.lc = lc.LanguageChecker() <5> self.mh = mh.mathsHelper() <6> # the one bit of text given to us to decrypt <7> self.text: str = text <8> logger.debug(f"The inputted text at __main__ is {self.text}") <9> self.basic = BasicParent(self.lc) <10> self.hash = HashParent() <11> self.encoding = EncodingParent(self.lc) <12> self.level: int = 1 <13> self.sickomode: bool = False <14> self.greppable: bool = grep <15> self.cipher = cipher <16> self.console = Console() <17> self.probability_distribution: dict = {} <18> self.what_to_choose: dict = {} <19>
===========unchanged ref 0=========== at: Decryptor.Encoding.encodingParent EncodingParent(lc) at: Decryptor.Hash.hashParent HashParent() at: Decryptor.basicEncryption.basic_parent BasicParent(lc) at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.Hash.hashParent HashParent() at: ciphey.Decryptor.basicEncryption.basic_parent BasicParent(lc) at: ciphey.LanguageChecker.iface LanguageChecker(config, params) at: ciphey.neuralNetworkMod.nn NeuralNetwork() at: neuralNetworkMod.nn NeuralNetwork() ===========changed ref 0=========== # module: ciphey.__main__ + """ + ██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ + ██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝ + ██║ ██║██████╔╝███████║█████╗ ╚████╔╝ + ██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝ + ╚██████╗██</s> ===========changed ref 1=========== # module: ciphey.__main__ # offset: 1 <s>╚██████╗██║██║ ██║ ██║███████╗ ██║ + © Brandon Skerritt + https://github.com/brandonskerritt/ciphey + The cycle goes: + main -> argparsing (if needed) -> call_encryption -> new Ciphey object -> decrypt() -> produceProbTable -> + one_level_of_decryption -> decrypt_normal + + Ciphey can be called 3 ways: + echo 'text' | ciphey + ciphey 'text' + ciphey -t 'text' + main captures the first 2 + argparsing captures the last one (-t) + it sends this to call_encryption, which can handle all 3 arguments using dict unpacking + + decrypt() creates the prob table and prints it. + + one_level_of_decryption() allows us to repeatedly call one_level_of_decryption on the inputs + so if something is doubly encrypted, we can use this to find it. + + Decrypt_normal is one round of decryption. We need one_level_of_decryption to call it, as + one_level_of_decryption handles progress bars and stuff. + """ + + - logger.add( - sys.stderr, - format="{time} {level} {message}", - filter="my_module", - level="DEBUG", - diagnose=True, - backtrace=True, - ) </s> ===========changed ref 2=========== # module: ciphey.__main__ # offset: 2 <s>filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: + from ciphey.LanguageChecker import LanguageChecker as lc - from ciphey.languageCheckerMod import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent - except ModuleNotFoundError: from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent - try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh
ciphey.__main__/Ciphey.decrypt
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<9>:<del> <38>:<add> logger.trace( <del> logger.debug(
# module: ciphey.__main__ class Ciphey: def decrypt(self): <0> """Performs the decryption of text <1> <2> Creates the probability table, calls one_level_of_decryption <3> <4> Args: <5> None, it uses class variables. <6> <7> Returns: <8> None <9> <10> """ <11> # Read the documentation for more on this function. <12> # checks to see if inputted text is plaintext <13> result = self.lc.checkLanguage(self.text) <14> if result: <15> print("You inputted plain text!") <16> print(f"Returning {self.text}") <17> return self.text <18> self.probability_distribution: dict = self.ai.predictnn(self.text)[0] <19> self.what_to_choose: dict = { <20> self.hash: { <21> "sha1": self.probability_distribution[0], <22> "md5": self.probability_distribution[1], <23> "sha256": self.probability_distribution[2], <24> "sha512": self.probability_distribution[3], <25> }, <26> self.basic: {"caesar": self.probability_distribution[4]}, <27> "plaintext": {"plaintext": self.probability_distribution[5]}, <28> self.encoding: { <29> "reverse": self.probability_distribution[6], <30> "base64": self.probability_distribution[7], <31> "binary": self.probability_distribution[8], <32> "hexadecimal": self.probability_distribution[9], <33> "ascii": self.probability_distribution[10], <34> "morse": self.probability_distribution[11], <35> }, <36> } <37> <38> logger.debug( <39> f"The probability table before 0.1 in __main__ is {self.what_to_choose}" <40> ) <41> <42> </s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): # offset: 1 for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. if v < 0.01: self.what_to_choose[key][k] = 0.01 logger.debug( f"The probability table after 0.1 in __main__ is {self.what_to_choose}" ) self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) # Creates and prints the probability table if not self.greppable: logger.debug(f"Self.greppable is {self.greppable}") self.produceprobtable(self.what_to_choose) logger.debug( f"The new probability table after sorting in __main__ is {self.what_to_choose}" ) """ #for each dictionary in the dictionary # sort that dictionary #sort the overall dictionary by the first value of the new dictionary """ output = None if self.level <= 1: output = self.one_level_of_decryption() else: if self.sickomode: print("Sicko mode entered") f = open("decryptionContents.txt", "w") output = self.one_level_of_decryption(file=f) for i in range(0, self.level): # open file and go through each text item pass logger.debug(f"decrypt is outputting {output}") return output ===========unchanged ref 0=========== at: Decryptor.Hash.hashParent HashParent() at: Decryptor.basicEncryption.basic_parent BasicParent(lc) at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.__main__.Ciphey produceprobtable(prob_table) -> None at: ciphey.mathsHelper mathsHelper() at: ciphey.neuralNetworkMod.nn.NeuralNetwork predictnn(text) at: mathsHelper.mathsHelper sort_prob_table(prob_table: dict) -> dict at: neuralNetworkMod.nn NeuralNetwork() at: sys stderr: TextIO at: typing.IO __slots__ = () isatty() -> bool ===========changed ref 0=========== # module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): - if not debug: + logger.remove() - logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) + logger.opt(colors=True) + logger.trace(f"""Finished argument object is {config}""") + logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() + self.lc = config["checker"](config) - self.lc = lc.LanguageChecker() self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt + self.text: str = config["ctext"] - self.text: str = text - logger.debug(f"The inputted text at __main__ is {self.text}") self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 - self.sickomode: bool = False + self.greppable: bool = config["grep"] - self.greppable: bool = grep + self.cipher_info = config["info"] - self.cipher = cipher self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 1=========== # module: ciphey.__main__ + """ + ██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗ + ██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝ + ██║ ██║██████╔╝███████║█████╗ ╚████╔╝ + ██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝ + ╚██████╗██</s>
ciphey.__main__/Ciphey.decrypt_normal
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<31>:<add> if self.cipher_info: <del> if self.cipher:
# module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: <0> """Called by one_level_of_decryption <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> bar -> whether or not to use alive_Bar <6> <7> Returns: <8> None, but prints. <9> <10> """ <11> result = self.lc.checkLanguage(self.text) <12> if result: <13> print("You inputted plain text!") <14> print(f"Returning {self.text}") <15> return self.text <16> <17> logger.debug(f"In decrypt_normal") <18> for key, val in self.what_to_choose.items(): <19> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <20> if not isinstance(key, str): <21> key.setProbTable(val) <22> ret: dict = key.decrypt(self.text) <23> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <24> logger.debug( <25> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <26> ) <27> <28> if ret["IsPlaintext?"]: <29> logger.debug(f"Ret is plaintext") <30> print(ret["Plaintext"]) <31> if self.cipher: <32> if ret["Extra Information"] is not None: <33> print( <34> "The cipher used is", <35> ret["Cipher"] + ".", <36> ret["Extra Information"] + ".", <37> ) <38> else: <39> print("The cipher used is " + ret["Cipher"] + ".") <40> return ret <41> <42> logger</s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: # offset: 1 print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey.__init__ self.lc = config["checker"](config) self.text: str = config["ctext"] self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.console = Console() self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) at: ciphey.__main__.Ciphey.produceprobtable table = Table(show_header=True, header_style="bold magenta") ===========changed ref 0=========== # module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): - if not debug: + logger.remove() - logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) + logger.opt(colors=True) + logger.trace(f"""Finished argument object is {config}""") + logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() + self.lc = config["checker"](config) - self.lc = lc.LanguageChecker() self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt + self.text: str = config["ctext"] - self.text: str = text - logger.debug(f"The inputted text at __main__ is {self.text}") self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 - self.sickomode: bool = False + self.greppable: bool = config["grep"] - self.greppable: bool = grep + self.cipher_info = config["info"] - self.cipher = cipher self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): """Performs the decryption of text Creates the probability table, calls one_level_of_decryption Args: None, it uses class variables. Returns: None - """ # Read the documentation for more on this function. # checks to see if inputted text is plaintext result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text self.probability_distribution: dict = self.ai.predictnn(self.text)[0] self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } + logger.trace( - logger.debug( f"The probability table before 0.1 in __main__ is {self.what_to_choose}" ) # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in</s>
ciphey.__main__/arg_parsing
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<5>:<del> A tuple containing the arguments, which is unpacked in main() <6>:<del> <7>:<add> The config to be passed around for the rest of time <14>:<del> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False) <15>:<del> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, <16>:<del> # the slower it is)' <17>:<del> # required=False) <24>:<add> default=False <26>:<del> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False) <28>:<add> "-i", <del> "-c", <29>:<add> "--info", <del> "--cipher", <33>:<add> default=False <34>:<del> # fake argument to stop argparser complaining about no arguments <35>:<del> # allows sys.argv to be used <36>:<del> # parser.add_argument("-m", action="store_false", default=True, required=False) <37>:<del>
# module: ciphey.__main__ + def arg_parsing() -> Optional[dict]: - def arg_parsing() -> dict: <0> """This function parses arguments. <1> <2> Args: <3> None <4> Returns: <5> A tuple containing the arguments, which is unpacked in main() <6> <7> """ <8> parser = argparse.ArgumentParser( <9> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n <10> Examples: <11> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true <12> """ <13> ) <14> # parser.add_argument('-f','--file', help='File you want to decrypt', required=False) <15> # parser.add_argument('-l','--level', help='How many levels of decryption you want (the more levels, <16> # the slower it is)' <17> # required=False) <18> parser.add_argument( <19> "-g", <20> "--greppable", <21> help="Only output the answer, no progress bars or information. Useful for grep", <22> action="store_true", <23> required=False, <24> ) <25> parser.add_argument("-t", "--text", help="Text to decrypt", required=False) <26> # parser.add_argument('-s','--sicko-mode', help='If it is encrypted Ciphey WILL find it', required=False) <27> parser.add_argument( <28> "-c", <29> "--cipher", <30> help="Do you want information on the cipher used?", <31> action="store_true", <32> required=False, <33> ) <34> # fake argument to stop argparser complaining about no arguments <35> # allows sys.argv to be used <36> # parser.add_argument("-m", action="store_false", default=True, required=False) <37> </s>
===========below chunk 0=========== # module: ciphey.__main__ + def arg_parsing() -> Optional[dict]: - def arg_parsing() -> dict: # offset: 1 "-d", "--debug", help="Activates debug mode", required=False, action="store_true", ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"]: text = args["text"] if args["text"] is None and len(sys.argv) > 1: text = args["rest"][0] if not sys.stdin.isatty(): text = str(sys.stdin.read()) if len(sys.argv) == 1 and text == None: print("No arguments were supplied. Look at the help menu with -h or --help") args["text"] = text if not args["rest"]: args.pop("rest") if len(args["text"]) < 3: print("Your inputted string is less than 3 chars, Ciphey cannot crack it.") return None return args ===========unchanged ref 0=========== at: argparse ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...) at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: ciphey.__main__.Ciphey.decrypt_normal ret: dict = key.decrypt(self.text) ===========changed ref 0=========== # module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): - if not debug: + logger.remove() - logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) + logger.opt(colors=True) + logger.trace(f"""Finished argument object is {config}""") + logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() + self.lc = config["checker"](config) - self.lc = lc.LanguageChecker() self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt + self.text: str = config["ctext"] - self.text: str = text - logger.debug(f"The inputted text at __main__ is {self.text}") self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 - self.sickomode: bool = False + self.greppable: bool = config["grep"] - self.greppable: bool = grep + self.cipher_info = config["info"] - self.cipher = cipher self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: None, but prints. """ result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) + if self.cipher_info: - if self.cipher: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher:</s> ===========changed ref 2=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: # offset: 1 <s>debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None
ciphey.__main__/main
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<2>:<add> It gets the arguments in the function definition using locals() <del> It gets the arguments in the function definition using locals(). <3>:<add> if withArgs is True, that means this is being called with command line args <del> if withArgs is True, that means this is being called with command line args. <4>:<add> so go to arg_parsing() to get those args <del> so go to arg_parsing() to get those args. <5>:<add> we then update locals() with the new command line args and remove "withArgs" <del> we then update locals() with the new command line args and remove "withArgs". <6>:<add> This function then calls call_encryption(**result) which passes our dict of args <del> This function then calls call_encryption(**result) which passes our dict of args. <11>:<add> """ <add> # We must fill in the arguments if they are not provided <add> if config is None: <add> args = arg_parsing() <add> # Check if we errored out <add> if args is None: <add> return None <12>:<del> """ <13>:<del> # testing is if we run pytest <14>:<del> result = locals() <15>:<del> if withArgs: <16>:<del> result.update(arg_parsing()) <17>:<del> result.pop("withArgs") <18>:<del> <19>:<del> output = call_encryption(**result) <20>:<del> return output <21>:<add> # Now we have working arguments, we can expand it and pass it to the Ciphey constructor <add> cipher_obj = Ciphey(args) <add> return cipher_obj.decrypt()
# module: ciphey.__main__ + def main(config: dict = None) -> Optional[str]: - def main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict: <0> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <1> <2> It gets the arguments in the function definition using locals(). <3> if withArgs is True, that means this is being called with command line args. <4> so go to arg_parsing() to get those args. <5> we then update locals() with the new command line args and remove "withArgs". <6> This function then calls call_encryption(**result) which passes our dict of args. <7> to the function as its own arguments using dict unpacking. <8> <9> Returns: <10> The output of the decryption. <11> <12> """ <13> # testing is if we run pytest <14> result = locals() <15> if withArgs: <16> result.update(arg_parsing()) <17> result.pop("withArgs") <18> <19> output = call_encryption(**result) <20> return output <21>
===========unchanged ref 0=========== at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: ciphey.__main__.arg_parsing parser = argparse.ArgumentParser( description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n Examples: python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true """ ) ===========changed ref 0=========== # module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): - if not debug: + logger.remove() - logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) + logger.opt(colors=True) + logger.trace(f"""Finished argument object is {config}""") + logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() + self.lc = config["checker"](config) - self.lc = lc.LanguageChecker() self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt + self.text: str = config["ctext"] - self.text: str = text - logger.debug(f"The inputted text at __main__ is {self.text}") self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 - self.sickomode: bool = False + self.greppable: bool = config["grep"] - self.greppable: bool = grep + self.cipher_info = config["info"] - self.cipher = cipher self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: None, but prints. """ result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) + if self.cipher_info: - if self.cipher: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher:</s> ===========changed ref 2=========== # module: ciphey.__main__ class Ciphey: def decrypt_normal(self, bar=None) -> None: # offset: 1 <s>debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========changed ref 3=========== # module: ciphey.__main__ class Ciphey: def decrypt(self): """Performs the decryption of text Creates the probability table, calls one_level_of_decryption Args: None, it uses class variables. Returns: None - """ # Read the documentation for more on this function. # checks to see if inputted text is plaintext result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text self.probability_distribution: dict = self.ai.predictnn(self.text)[0] self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } + logger.trace( - logger.debug( f"The probability table before 0.1 in __main__ is {self.what_to_choose}" ) # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in</s>
ciphey.LanguageChecker.brandon/Brandon.check1000Words
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<17>:<add> logger.trace(f"text before cleaning is {text}") <del> logger.debug(f"text before cleaning is {text}") <19>:<add> logger.trace(f"Check 1000 words text is {text}") <del> logger.debug(f"Check 1000 words text is {text}") <23>:<del> logger.debug(f"Word in check1000 is {word}") <27>:<del> logger.debug(f"Check 1000 words returns True for word {word}")
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def check1000Words(self, text: str) -> bool: <0> """Checks to see if word is in the list of 1000 words <1> <2> the 1000words is a dict, so lookup is O(1) <3> <4> Args: <5> text -> The text we use to text (a word) <6> <7> Returns: <8> bool -> whether it's in the dict or not. <9> <10> """ <11> # If we have no wordlist, then we can't reject the candidate on this basis <12> if self.top1000Words is None: <13> return True <14> <15> if text is None: <16> return False <17> logger.debug(f"text before cleaning is {text}") <18> text = self.cleanText(text) <19> logger.debug(f"Check 1000 words text is {text}") <20> # If any of the top 1000 words in the text appear <21> # return true <22> for word in text: <23> logger.debug(f"Word in check1000 is {word}") <24> # I was debating using any() here, but I think they're the <25> # same speed so it doesn't really matter too much <26> if word in self.top1000Words: <27> logger.debug(f"Check 1000 words returns True for word {word}") <28> return True <29> return False <30>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon.Brandon cleanText(text: str) -> set at: ciphey.LanguageChecker.brandon.Brandon.__init__ self.top1000Words = config["params"].get("top1000") ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 2=========== # module: ciphey.__main__ if __name__ == "__main__": # withArgs because this function is only called # if the program is run in terminal + main() - main(withArgs=True) ===========changed ref 3=========== # module: ciphey.__main__ - - - def call_encryption( - greppable=False, Cipher=False, text=None, debug=False, cipher=False - ): - """Function to call Encryption, only used because of arguments. - - Basically, this is what Main used to be before I had to deal with arg parsing - - Returns: - The output of the decryption. - - """ - output = None - if text is not None: - cipher_obj = Ciphey(text, greppable, Cipher, debug) - output = cipher_obj.decrypt() - return output - ===========changed ref 4=========== # module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): - if not debug: + logger.remove() - logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) + logger.opt(colors=True) + logger.trace(f"""Finished argument object is {config}""") + logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() + self.lc = config["checker"](config) - self.lc = lc.LanguageChecker() self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt + self.text: str = config["ctext"] - self.text: str = text - logger.debug(f"The inputted text at __main__ is {self.text}") self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 - self.sickomode: bool = False + self.greppable: bool = config["grep"] - self.greppable: bool = grep + self.cipher_info = config["info"] - self.cipher = cipher self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 5=========== # module: ciphey.__main__ + def main(config: dict = None) -> Optional[str]: - def main(greppable=False, Cipher=False, text=None, debug=False, withArgs=False) -> dict: """Function to deal with arguments. Either calls with args or not. Makes Pytest work. + It gets the arguments in the function definition using locals() - It gets the arguments in the function definition using locals(). + if withArgs is True, that means this is being called with command line args - if withArgs is True, that means this is being called with command line args. + so go to arg_parsing() to get those args - so go to arg_parsing() to get those args. + we then update locals() with the new command line args and remove "withArgs" - 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 - 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. + """ + # We must fill in the arguments if they are not provided + if config is None: + args = arg_parsing() + # Check if we errored out + if args is None: + return None - """ - # testing is if we run pytest - result = locals() - if withArgs: - result.update(arg_parsing()) - result.pop("withArgs") - - output = call_encryption(**result) - return output + # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(args) + return cipher_obj.decrypt()
ciphey.LanguageChecker.brandon/Brandon.confirmLanguage
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<2>:<add> If the proportion (taken from checkDictionary) is higher than the language threshold, return True <del> If the languagePercentage (taken from checkDictionary) is higher than the language threshold, return True <12>:<add> <add> proportion = self.checkWordlist(text) <del> self.checkDictionary(text) <13>:<add> if self.checkWordlist(text) >= self.languageThreshold: <del> if self.languagePercentage >= self.languageThreshold: <14>:<add> logger.trace( <del> logger.debug( <15>:<add> f"The language proportion {proportion} is over the threshold {self.languageThreshold}" <del> f"The language percentage {self.languagePercentage} is over the threshold {self.languageThreshold}"
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def confirmLanguage(self, text: str) -> True: <0> """Confirms whether given text is language <1> <2> If the languagePercentage (taken from checkDictionary) is higher than the language threshold, return True <3> <4> Args: <5> text -> The text we use to text (a word) <6> language -> the language we use to check <7> <8> Returns: <9> bool -> whether it's written in Language or not <10> <11> """ <12> self.checkDictionary(text) <13> if self.languagePercentage >= self.languageThreshold: <14> logger.debug( <15> f"The language percentage {self.languagePercentage} is over the threshold {self.languageThreshold}" <16> ) <17> return True <18> else: <19> return False <20>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon.Brandon checkWordlist(text: str) -> float at: ciphey.LanguageChecker.brandon.Brandon.__init__ self.languageThreshold = config["params"].get("threshold", 0.55) ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 2=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def check1000Words(self, text: str) -> bool: """Checks to see if word is in the list of 1000 words the 1000words is a dict, so lookup is O(1) Args: text -> The text we use to text (a word) Returns: bool -> whether it's in the dict or not. """ # If we have no wordlist, then we can't reject the candidate on this basis if self.top1000Words is None: return True if text is None: return False + logger.trace(f"text before cleaning is {text}") - logger.debug(f"text before cleaning is {text}") text = self.cleanText(text) + logger.trace(f"Check 1000 words text is {text}") - logger.debug(f"Check 1000 words text is {text}") # If any of the top 1000 words in the text appear # return true for word in text: - logger.debug(f"Word in check1000 is {word}") # I was debating using any() here, but I think they're the # same speed so it doesn't really matter too much if word in self.top1000Words: - logger.debug(f"Check 1000 words returns True for word {word}") return True return False ===========changed ref 3=========== # module: ciphey.__main__ if __name__ == "__main__": # withArgs because this function is only called # if the program is run in terminal + main() - main(withArgs=True) ===========changed ref 4=========== # module: ciphey.__main__ - - - def call_encryption( - greppable=False, Cipher=False, text=None, debug=False, cipher=False - ): - """Function to call Encryption, only used because of arguments. - - Basically, this is what Main used to be before I had to deal with arg parsing - - Returns: - The output of the decryption. - - """ - output = None - if text is not None: - cipher_obj = Ciphey(text, greppable, Cipher, debug) - output = cipher_obj.decrypt() - return output - ===========changed ref 5=========== # module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): - if not debug: + logger.remove() - logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) + logger.opt(colors=True) + logger.trace(f"""Finished argument object is {config}""") + logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() + self.lc = config["checker"](config) - self.lc = lc.LanguageChecker() self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt + self.text: str = config["ctext"] - self.text: str = text - logger.debug(f"The inputted text at __main__ is {self.text}") self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 - self.sickomode: bool = False + self.greppable: bool = config["grep"] - self.greppable: bool = grep + self.cipher_info = config["info"] - self.cipher = cipher self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {}
ciphey.LanguageChecker.brandon/Brandon.__init__
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<0>:<add> # Suppresses warning <del> # Supresses warning <1>:<add> super().__init__(config) <del> super().__init__(config, params) <3>:<del> self.languagePercentage: float = 0.0 <4>:<del> self.languageWordsCounter: float = 0.0 <5>:<del> self.languageThreshold = 55 <6>:<add> self.languageThreshold = config["params"].get("threshold", 0.55) <add> self.top1000Words = config["params"].get("top1000") <del> self.top1000Words = params.get("top1000") <7>:<add> self.wordlist = config["wordlist"] <del> self.wordlist = config.get("wordlist")
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def __init__(self, config): - def __init__(self, config, params): <0> # Supresses warning <1> super().__init__(config, params) <2> self.mh = mh.mathsHelper() <3> self.languagePercentage: float = 0.0 <4> self.languageWordsCounter: float = 0.0 <5> self.languageThreshold = 55 <6> self.top1000Words = params.get("top1000") <7> self.wordlist = config.get("wordlist") <8>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.iface.LanguageChecker checkLanguage(self, text: str) -> bool __init__(config, params) __init__(self, config, params) at: ciphey.mathsHelper mathsHelper() ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 2=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def confirmLanguage(self, text: str) -> True: """Confirms whether given text is language + If the proportion (taken from checkDictionary) is higher than the language threshold, return True - If the languagePercentage (taken from checkDictionary) is higher than the language threshold, return True Args: text -> The text we use to text (a word) language -> the language we use to check Returns: bool -> whether it's written in Language or not """ + + proportion = self.checkWordlist(text) - self.checkDictionary(text) + if self.checkWordlist(text) >= self.languageThreshold: - if self.languagePercentage >= self.languageThreshold: + logger.trace( - logger.debug( + f"The language proportion {proportion} is over the threshold {self.languageThreshold}" - f"The language percentage {self.languagePercentage} is over the threshold {self.languageThreshold}" ) return True else: return False ===========changed ref 3=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def check1000Words(self, text: str) -> bool: """Checks to see if word is in the list of 1000 words the 1000words is a dict, so lookup is O(1) Args: text -> The text we use to text (a word) Returns: bool -> whether it's in the dict or not. """ # If we have no wordlist, then we can't reject the candidate on this basis if self.top1000Words is None: return True if text is None: return False + logger.trace(f"text before cleaning is {text}") - logger.debug(f"text before cleaning is {text}") text = self.cleanText(text) + logger.trace(f"Check 1000 words text is {text}") - logger.debug(f"Check 1000 words text is {text}") # If any of the top 1000 words in the text appear # return true for word in text: - logger.debug(f"Word in check1000 is {word}") # I was debating using any() here, but I think they're the # same speed so it doesn't really matter too much if word in self.top1000Words: - logger.debug(f"Check 1000 words returns True for word {word}") return True return False ===========changed ref 4=========== # module: ciphey.__main__ if __name__ == "__main__": # withArgs because this function is only called # if the program is run in terminal + main() - main(withArgs=True) ===========changed ref 5=========== # module: ciphey.__main__ - - - def call_encryption( - greppable=False, Cipher=False, text=None, debug=False, cipher=False - ): - """Function to call Encryption, only used because of arguments. - - Basically, this is what Main used to be before I had to deal with arg parsing - - Returns: - The output of the decryption. - - """ - output = None - if text is not None: - cipher_obj = Ciphey(text, greppable, Cipher, debug) - output = cipher_obj.decrypt() - return output - ===========changed ref 6=========== # module: ciphey.__main__ class Ciphey: + + def __init__(self, config): - def __init__(self, text, grep=False, cipher=False, debug=False): - if not debug: + logger.remove() - logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) + logger.opt(colors=True) + logger.trace(f"""Finished argument object is {config}""") + logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() + self.lc = config["checker"](config) - self.lc = lc.LanguageChecker() self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt + self.text: str = config["ctext"] - self.text: str = text - logger.debug(f"The inputted text at __main__ is {self.text}") self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 - self.sickomode: bool = False + self.greppable: bool = config["grep"] - self.greppable: bool = grep + self.cipher_info = config["info"] - self.cipher = cipher self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {}
ciphey.LanguageChecker.brandon/Brandon.checkLanguage
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<1>:<del> Uses chisqaured <12>:<add> logger.trace(f"In Language Checker with {text}") <del> logger.debug(f"In Language Checker with {text}") <15>:<add> if not self.check1000Words(text): <del> if not self.dictionary.check1000Words(text): <21>:<add> logger.trace( <del> logger.debug( <22>:<add> f"1000words check passed" <del> f"Language check phase 1 complete" <24>:<add> result2: bool = self.confirmLanguage(text) <del> result2: bool = self.dictionary.confirmLanguage(text, "english") <25>:<del> logger.debug(f"Result is, dictionary checker, is {result2}") <27>:<add> logger.debug(f"Dictionary check failed. This is not plaintext") <del> logger.debug(f"Language check phase 2 returns false") <29>:<add> <add> logger.trace(f"Dictionary check passed. This is plaintext")
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def checkLanguage(self, text: str) -> bool: <0> """Checks to see if the text is in English <1> Uses chisqaured <2> <3> Performs a decryption, but mainly parses the internal data packet and prints useful information. <4> <5> Args: <6> text -> The text we use to perform analysis on <7> <8> Returns: <9> bool -> True if the text is English, False otherwise. <10> <11> """ <12> logger.debug(f"In Language Checker with {text}") <13> if text == "": <14> return False <15> if not self.dictionary.check1000Words(text): <16> logger.debug( <17> f"1000 words failed. This is not plaintext" <18> ) <19> return False <20> <21> logger.debug( <22> f"Language check phase 1 complete" <23> ) <24> result2: bool = self.dictionary.confirmLanguage(text, "english") <25> logger.debug(f"Result is, dictionary checker, is {result2}") <26> if not result2: <27> logger.debug(f"Language check phase 2 returns false") <28> return False <29> return True <30>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon.Brandon check1000Words(text: str) -> bool check1000Words(self, text: str) -> bool confirmLanguage(text: str) -> True confirmLanguage(self, text: str) -> True at: ciphey.LanguageChecker.iface.LanguageChecker getArgs(**kwargs) -> dict ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def confirmLanguage(self, text: str) -> True: """Confirms whether given text is language + If the proportion (taken from checkDictionary) is higher than the language threshold, return True - If the languagePercentage (taken from checkDictionary) is higher than the language threshold, return True Args: text -> The text we use to text (a word) language -> the language we use to check Returns: bool -> whether it's written in Language or not """ + + proportion = self.checkWordlist(text) - self.checkDictionary(text) + if self.checkWordlist(text) >= self.languageThreshold: - if self.languagePercentage >= self.languageThreshold: + logger.trace( - logger.debug( + f"The language proportion {proportion} is over the threshold {self.languageThreshold}" - f"The language percentage {self.languagePercentage} is over the threshold {self.languageThreshold}" ) return True else: return False ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def check1000Words(self, text: str) -> bool: """Checks to see if word is in the list of 1000 words the 1000words is a dict, so lookup is O(1) Args: text -> The text we use to text (a word) Returns: bool -> whether it's in the dict or not. """ # If we have no wordlist, then we can't reject the candidate on this basis if self.top1000Words is None: return True if text is None: return False + logger.trace(f"text before cleaning is {text}") - logger.debug(f"text before cleaning is {text}") text = self.cleanText(text) + logger.trace(f"Check 1000 words text is {text}") - logger.debug(f"Check 1000 words text is {text}") # If any of the top 1000 words in the text appear # return true for word in text: - logger.debug(f"Word in check1000 is {word}") # I was debating using any() here, but I think they're the # same speed so it doesn't really matter too much if word in self.top1000Words: - logger.debug(f"Check 1000 words returns True for word {word}") return True return False ===========changed ref 2=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def __init__(self, config): - def __init__(self, config, params): + # Suppresses warning - # Supresses warning + super().__init__(config) - super().__init__(config, params) self.mh = mh.mathsHelper() - self.languagePercentage: float = 0.0 - self.languageWordsCounter: float = 0.0 - self.languageThreshold = 55 + self.languageThreshold = config["params"].get("threshold", 0.55) + self.top1000Words = config["params"].get("top1000") - self.top1000Words = params.get("top1000") + self.wordlist = config["wordlist"] - self.wordlist = config.get("wordlist") ===========changed ref 3=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 4=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 5=========== # module: ciphey.__main__ if __name__ == "__main__": # withArgs because this function is only called # if the program is run in terminal + main() - main(withArgs=True) ===========changed ref 6=========== # module: ciphey.__main__ - - - def call_encryption( - greppable=False, Cipher=False, text=None, debug=False, cipher=False - ): - """Function to call Encryption, only used because of arguments. - - Basically, this is what Main used to be before I had to deal with arg parsing - - Returns: - The output of the decryption. - - """ - output = None - if text is not None: - cipher_obj = Ciphey(text, greppable, Cipher, debug) - output = cipher_obj.decrypt() - return output -
ciphey.LanguageChecker.brandon/Brandon.getArgs
Modified
Ciphey~Ciphey
22a1f05fad6e2b4356f77562329934911d2e8282
It sort of works now
<1>:<add> "top1000": {"desc": "A json dictionary of the top 1000 words", "req": False}, <del> "top1000": {"desc": "A path to a json dictionaty of the top 1000 words", "req": True} <2>:<add> "threshold": {"desc": "The minimum proportion (between 0 and 1) that must be in the dictionary", "req": False}
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): @staticmethod def getArgs(**kwargs) -> dict: <0> return { <1> "top1000": {"desc": "A path to a json dictionaty of the top 1000 words", "req": True} <2> } <3>
===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def __init__(self, config): - def __init__(self, config, params): + # Suppresses warning - # Supresses warning + super().__init__(config) - super().__init__(config, params) self.mh = mh.mathsHelper() - self.languagePercentage: float = 0.0 - self.languageWordsCounter: float = 0.0 - self.languageThreshold = 55 + self.languageThreshold = config["params"].get("threshold", 0.55) + self.top1000Words = config["params"].get("top1000") - self.top1000Words = params.get("top1000") + self.wordlist = config["wordlist"] - self.wordlist = config.get("wordlist") ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 2=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): - - def checkDictionary(self, text: str) -> int: - """Sorts & searches the dict - - Args: - text -> The text we use to perform analysis on - language -> the language we want to check - - Returns: - counter -> how many words in text, are in the dict of language - - """ - # reads through most common words / passwords - # and calculates how much of that is in language - text: set = self.cleanText(text) - - return len(text.intersection(self.wordlist)) - ===========changed ref 3=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def confirmLanguage(self, text: str) -> True: """Confirms whether given text is language + If the proportion (taken from checkDictionary) is higher than the language threshold, return True - If the languagePercentage (taken from checkDictionary) is higher than the language threshold, return True Args: text -> The text we use to text (a word) language -> the language we use to check Returns: bool -> whether it's written in Language or not """ + + proportion = self.checkWordlist(text) - self.checkDictionary(text) + if self.checkWordlist(text) >= self.languageThreshold: - if self.languagePercentage >= self.languageThreshold: + logger.trace( - logger.debug( + f"The language proportion {proportion} is over the threshold {self.languageThreshold}" - f"The language percentage {self.languagePercentage} is over the threshold {self.languageThreshold}" ) return True else: return False ===========changed ref 4=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def checkLanguage(self, text: str) -> bool: """Checks to see if the text is in English - Uses chisqaured Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: text -> The text we use to perform analysis on Returns: bool -> True if the text is English, False otherwise. """ + logger.trace(f"In Language Checker with {text}") - logger.debug(f"In Language Checker with {text}") if text == "": return False + if not self.check1000Words(text): - if not self.dictionary.check1000Words(text): logger.debug( f"1000 words failed. This is not plaintext" ) return False + logger.trace( - logger.debug( + f"1000words check passed" - f"Language check phase 1 complete" ) + result2: bool = self.confirmLanguage(text) - result2: bool = self.dictionary.confirmLanguage(text, "english") - logger.debug(f"Result is, dictionary checker, is {result2}") if not result2: + logger.debug(f"Dictionary check failed. This is not plaintext") - logger.debug(f"Language check phase 2 returns false") return False + + logger.trace(f"Dictionary check passed. This is plaintext") return True ===========changed ref 5=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def check1000Words(self, text: str) -> bool: """Checks to see if word is in the list of 1000 words the 1000words is a dict, so lookup is O(1) Args: text -> The text we use to text (a word) Returns: bool -> whether it's in the dict or not. """ # If we have no wordlist, then we can't reject the candidate on this basis if self.top1000Words is None: return True if text is None: return False + logger.trace(f"text before cleaning is {text}") - logger.debug(f"text before cleaning is {text}") text = self.cleanText(text) + logger.trace(f"Check 1000 words text is {text}") - logger.debug(f"Check 1000 words text is {text}") # If any of the top 1000 words in the text appear # return true for word in text: - logger.debug(f"Word in check1000 is {word}") # I was debating using any() here, but I think they're the # same speed so it doesn't really matter too much if word in self.top1000Words: - logger.debug(f"Check 1000 words returns True for word {word}") return True return False ===========changed ref 6=========== # module: ciphey.__main__ if __name__ == "__main__": # withArgs because this function is only called # if the program is run in terminal + main() - main(withArgs=True) ===========changed ref 7=========== # module: ciphey.__main__ - - - def call_encryption( - greppable=False, Cipher=False, text=None, debug=False, cipher=False - ): - """Function to call Encryption, only used because of arguments. - - Basically, this is what Main used to be before I had to deal with arg parsing - - Returns: - The output of the decryption. - - """ - output = None - if text is not None: - cipher_obj = Ciphey(text, greppable, Cipher, debug) - output = cipher_obj.decrypt() - return output -
ciphey.__main__/arg_parsing
Modified
Ciphey~Ciphey
911d051ca40d93fb6a849cccd0806e5a0478f3e8
added docs on brandon's request
# module: ciphey.__main__ def arg_parsing() -> Optional[dict]: <0> """This function parses arguments. <1> <2> Args: <3> None <4> Returns: <5> The config to be passed around for the rest of time <6> """ <7> parser = argparse.ArgumentParser( <8> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n <9> Examples: <10> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true <11> """ <12> ) <13> parser.add_argument( <14> "-g", <15> "--greppable", <16> help="Only output the answer, no progress bars or information. Useful for grep", <17> action="store_true", <18> required=False, <19> default=False <20> ) <21> parser.add_argument("-t", "--text", help="Text to decrypt", required=False) <22> parser.add_argument( <23> "-i", <24> "--info", <25> help="Do you want information on the cipher used?", <26> action="store_true", <27> required=False, <28> default=False <29> ) <30> parser.add_argument( <31> "-d", <32> "--debug", <33> help="Activates debug mode", # Actually "INFO" level is used, but ¯\_(ツ)_/¯ <34> required=False, <35> action="store_true", <36> ) <37> parser.add_argument( <38> "-D", <39> "--trace", <40> help="More verbose than debug mode. Shadows --debug", <41> required=False, <42> action="store_true", <43> ) <44> parser.add_argument( <45> "-q", <46> "--quiet", <47> help="Supress</s>
===========below chunk 0=========== # module: ciphey.__main__ def arg_parsing() -> Optional[dict]: # offset: 1 required=False, action="store_true", ) parser.add_argument( "-a", "--checker", help="Uses the given internal language checker. Defaults to brandon", required=False, ) parser.add_argument( "-A", "--checker-file", help="Uses the language checker at the given path", required=False, ) parser.add_argument( "-w", "--wordlist", help="Uses the given internal wordlist", required=False, ) parser.add_argument( "-W", "--wordlist-file", help="Uses the wordlist at the given path", required=False, ) parser.add_argument( "-p", "--param", help="Passes a parameter to the language checker", action="append", required=False, default=[] ) parser.add_argument( "-l", "--list-params", help="Lists the parameters of the selected module", action="store_true", required=False, ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"] is not None: text = args["text"] elif len(sys</s> ===========below chunk 1=========== # module: ciphey.__main__ def arg_parsing() -> Optional[dict]: # offset: 2 <s> = None if args["text"] is not None: text = args["text"] elif len(sys.argv) > 1: text = args["rest"][0] elif not sys.stdin.isatty(): text = str(sys.stdin.read()) else: print("No text input given!") return None if len(sys.argv) == 1: print("No arguments were supplied. Look at the help menu with -h or --help") return None args["text"] = text if not args["rest"]: args.pop("rest") if len(args["text"]) < 3: print("A string of less than 3 chars cannot be interpreted by Ciphey.") return None config = dict() # Now we can walk through the arguments, expanding them into a canonical form # # First, we go over simple args config["ctext"] = args["text"] config["grep"] = args["greppable"] config["info"] = args["info"] # Try to work out how verbose we should be if args["trace"]: config["debug"] = "TRACE" elif args["debug"]: config["debug"] = "DEBUG" elif args["quiet"]: config["debug"] = "ERROR" else: config["debug"] = "WARNING" # Try to locate language checker module # TODO: actually implement this from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon config["checker"] = brandon # Try to locate language checker module # TODO</s> ===========below chunk 2=========== # module: ciphey.__main__ def arg_parsing() -> Optional[dict]: # offset: 3 <s> implement this (should be similar) import cipheydists config["wordlist"] = cipheydists.get_list("english") # Now we fill in the params *shudder* config["params"] = {} for i in args["param"]: key, value = i.split('=', 1) config["params"][key] = value return config ===========unchanged ref 0=========== at: argparse REMAINDER = '...' ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...) at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: ciphey.LanguageChecker.brandon ciphey_language_checker = Brandon at: sys argv: List[str] stdin: TextIO at: typing.IO __slots__ = () isatty() -> bool read(n: int=...) -> AnyStr at: typing.MutableMapping pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] pop(key: _KT) -> _VT
ciphey.Decryptor.Encoding.encodingParent/EncodingParent.decrypt
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<19>:<add> if answer is not None and answer["IsPlaintext?"]: <del> if answer["IsPlaintext?"]:
# module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): <0> self.text = text <1> torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] <2> logger.debug(f"Encoding parent is running {torun}") <3> """ <4> ok so I have an array of functions <5> and I want to apply each function to some text <6> (text, function) <7> but the way it works is you apply text to every item in the array (function) <8> <9> """ <10> from multiprocessing.dummy import Pool as ThreadPool <11> <12> pool = ThreadPool(4) <13> answers = pool.map(self.callDecrypt, torun) <14> <15> for answer in answers: <16> logger.debug(f"All answers are {answers}") <17> # adds the LC objects together <18> # self.lc = self.lc + answer["lc"] <19> if answer["IsPlaintext?"]: <20> logger.debug(f"Plaintext found {answer}") <21> return answer <22> return { <23> "lc": self.lc, <24> "IsPlaintext?": False, <25> "Plaintext": None, <26> "Cipher": None, <27> "Extra Information": None, <28> } <29>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent callDecrypt(obj) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent.__init__ self.lc = lc self.base64 = Bases(self.lc) self.binary = Binary(self.lc) self.hex = Hexadecimal(self.lc) self.ascii = Ascii(self.lc) self.morse = MorseCode(self.lc) at: multiprocessing.dummy Pool(processes: Optional[int]=..., initializer: Optional[Callable[..., Any]]=..., initargs: Iterable[Any]=...) -> Any
ciphey.__main__/Ciphey.decrypt_normal
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<8>:<add> str if found, or None if not <del> None, but prints.
# module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: <0> """Called by one_level_of_decryption <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> bar -> whether or not to use alive_Bar <6> <7> Returns: <8> None, but prints. <9> <10> """ <11> result = self.lc.checkLanguage(self.text) <12> if result: <13> print("You inputted plain text!") <14> print(f"Returning {self.text}") <15> return self.text <16> <17> logger.debug(f"In decrypt_normal") <18> for key, val in self.what_to_choose.items(): <19> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <20> if not isinstance(key, str): <21> key.setProbTable(val) <22> ret: dict = key.decrypt(self.text) <23> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <24> logger.debug( <25> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <26> ) <27> <28> if ret["IsPlaintext?"]: <29> logger.debug(f"Ret is plaintext") <30> print(ret["Plaintext"]) <31> if self.cipher_info: <32> if ret["Extra Information"] is not None: <33> print( <34> "The cipher used is", <35> ret["Cipher"] + ".", <36> ret["Extra Information"] + ".", <37> ) <38> else: <39> print("The cipher used is "</s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: # offset: 1 return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey config = dict() params = dict() at: ciphey.__main__.Ciphey.__init__ self.lc = config["checker"](config) self.text: str = config["ctext"] self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) ===========changed ref 0=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, }
ciphey.__main__/main
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<14>:<add> config = arg_parsing() <del> args = arg_parsing() <16>:<add> if config is None: <del> if args is None: <20>:<add> cipher_obj = Ciphey(config) <del> cipher_obj = Ciphey(args)
# module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: <0> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <1> <2> It gets the arguments in the function definition using locals() <3> if withArgs is True, that means this is being called with command line args <4> so go to arg_parsing() to get those args <5> we then update locals() with the new command line args and remove "withArgs" <6> This function then calls call_encryption(**result) which passes our dict of args <7> to the function as its own arguments using dict unpacking. <8> <9> Returns: <10> The output of the decryption. <11> """ <12> # We must fill in the arguments if they are not provided <13> if config is None: <14> args = arg_parsing() <15> # Check if we errored out <16> if args is None: <17> return None <18> <19> # Now we have working arguments, we can expand it and pass it to the Ciphey constructor <20> cipher_obj = Ciphey(args) <21> return cipher_obj.decrypt() <22>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon ciphey_language_checker = Brandon at: ciphey.__main__.arg_parsing args["text"] = text at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: + str if found, or None if not - None, but prints. """ result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) if self.cipher_info: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") </s> ===========changed ref 2=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: # offset: 1 <s> used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, }
tests.test_encoding/TestEncoding.test_english_yes
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> lc = Brandon(config) <del> lc = LanguageChecker.LanguageChecker()
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): <0> lc = LanguageChecker.LanguageChecker() <1> ep = EncodingParent(lc) <2> result = ep.decrypt("eW91ciB0ZXh0") <3> self.assertEqual(result["IsPlaintext?"], True) <4>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon Brandon(config: Dict[str, object]) at: tests.test_encoding config = {"wordlist": cipheydists.get_list("english"), "params": {}} at: unittest.case TestCase(methodName: str=...) ===========changed ref 0=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 1=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 2=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt() ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 4=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: + str if found, or None if not - None, but prints. """ result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) if self.cipher_info: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") </s> ===========changed ref 5=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: # offset: 1 <s> used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None
tests.test_encoding/TestEncoding.test_base64_spaces_yes
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> lc = Brandon(config) <del> lc = LanguageChecker.LanguageChecker()
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): <0> lc = LanguageChecker.LanguageChecker() <1> ep = EncodingParent(lc) <2> result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") <3> self.assertEqual(result["IsPlaintext?"], True) <4>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent decrypt(text) at: ciphey.LanguageChecker.brandon Brandon(config: Dict[str, object]) at: tests.test_encoding config = {"wordlist": cipheydists.get_list("english"), "params": {}} at: tests.test_encoding.TestEncoding.test_english_yes ep = EncodingParent(lc) at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str _testMethodDoc: str assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 1=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 2=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 3=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 4=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt() ===========changed ref 5=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: + str if found, or None if not - None, but prints. """ result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) if self.cipher_info: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") </s> ===========changed ref 6=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: # offset: 1 <s> used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None
tests.test_encoding/TestEncoding.test_binary_spaces_yes
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> lc = Brandon(config) <del> lc = LanguageChecker.LanguageChecker()
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_binary_spaces_yes(self): <0> lc = LanguageChecker.LanguageChecker() <1> ep = EncodingParent(lc) <2> result = ep.decrypt( <3> "01001000 01100101 01101100 01101100 01101111 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 01110011 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100 01110011" <4> ) <5> self.assertEqual(result["IsPlaintext?"], True) <6>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent decrypt(text) at: ciphey.LanguageChecker.brandon Brandon(config: Dict[str, object]) at: tests.test_encoding config = {"wordlist": cipheydists.get_list("english"), "params": {}} at: tests.test_encoding.TestEncoding.test_base64_spaces_yes ep = EncodingParent(lc) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 1=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 2=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 3=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 4=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 5=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt() ===========changed ref 6=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[str]: - def decrypt_normal(self, bar=None) -> None: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: + str if found, or None if not - None, but prints. """ result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") return self.text logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) if self.cipher_info: if ret["Extra Information"] is not None: print( "The cipher used is", ret["Cipher"] + ".", ret["Extra Information"] + ".", ) else: print("The cipher used is " + ret["Cipher"] + ".") return ret logger.debug("No encryption found") </s>
tests.test_encoding/TestEncoding.test_hex_spaces_yes
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> lc = Brandon(config) <del> lc = LanguageChecker.LanguageChecker() <2>:<del> a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" <3>:<del> a = a.replace(" ", "") <4>:<add> result = ep.decrypt( <del> result = ep.decrypt(a) <5>:<add> "68 65 6c 6c 6f 20 6f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" <add> )
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_hex_spaces_yes(self): <0> lc = LanguageChecker.LanguageChecker() <1> ep = EncodingParent(lc) <2> a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" <3> a = a.replace(" ", "") <4> result = ep.decrypt(a) <5> self.assertEqual(result["IsPlaintext?"], True) <6>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.LanguageChecker.brandon Brandon(config: Dict[str, object]) at: tests.test_encoding config = {"wordlist": cipheydists.get_list("english"), "params": {}} at: tests.test_encoding.TestEncoding.test_hex_spaces_yes result = ep.decrypt( "68 65 6c 6c 6f 20 6f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" ) at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 1=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 2=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 3=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_binary_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt( "01001000 01100101 01101100 01101100 01101111 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 01110011 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100 01110011" ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 4=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 5=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt() ===========changed ref 6=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, }
tests.test_encoding/TestEncoding.test_ascii
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> lc = Brandon(config) <del> lc = LanguageChecker.LanguageChecker()
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_ascii(self): <0> lc = LanguageChecker.LanguageChecker() <1> ep = EncodingParent(lc) <2> a = "68 65 6C 6C 6F 20 64 6F 67" <3> result = ep.decrypt(a) <4> self.assertEqual(result["IsPlaintext?"], True) <5>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent decrypt(text) at: ciphey.LanguageChecker.brandon Brandon(config: Dict[str, object]) at: tests.test_encoding config = {"wordlist": cipheydists.get_list("english"), "params": {}} at: tests.test_encoding.TestEncoding.test_hex_mixed_spaces_yes ep = EncodingParent(lc) a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" a = a.replace(" ", "") at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 1=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 2=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 3=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 4=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): + def test_hex_mixed_spaces_yes(self): + lc = Brandon(config) + ep = EncodingParent(lc) + a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + a = a.replace(" ", "") + result = ep.decrypt(a) + self.assertEqual(result["IsPlaintext?"], True) + ===========changed ref 5=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_binary_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt( "01001000 01100101 01101100 01101100 01101111 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 01110011 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100 01110011" ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 6=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_hex_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) - a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" - a = a.replace(" ", "") + result = ep.decrypt( - result = ep.decrypt(a) + "68 65 6c 6c 6f 20 6f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 7=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 8=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt()
tests.test_encoding/TestEncoding.test_morse
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> lc = Brandon(config) <del> lc = LanguageChecker.LanguageChecker()
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_morse(self): <0> lc = LanguageChecker.LanguageChecker() <1> ep = EncodingParent(lc) <2> a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." <3> result = ep.decrypt(a) <4> self.assertEqual(result["IsPlaintext?"], True) <5>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent decrypt(text) at: ciphey.LanguageChecker.brandon Brandon(config: Dict[str, object]) at: tests.test_encoding config = {"wordlist": cipheydists.get_list("english"), "params": {}} at: tests.test_encoding.TestEncoding.test_ascii ep = EncodingParent(lc) a = "68 65 6C 6C 6F 20 64 6F 67" at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 1=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_ascii(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = "68 65 6C 6C 6F 20 64 6F 67" result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 2=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 3=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 4=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): + def test_hex_mixed_spaces_yes(self): + lc = Brandon(config) + ep = EncodingParent(lc) + a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + a = a.replace(" ", "") + result = ep.decrypt(a) + self.assertEqual(result["IsPlaintext?"], True) + ===========changed ref 5=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 6=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_binary_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt( "01001000 01100101 01101100 01101100 01101111 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 01110011 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100 01110011" ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 7=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_hex_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) - a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" - a = a.replace(" ", "") + result = ep.decrypt( - result = ep.decrypt(a) + "68 65 6c 6c 6f 20 6f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 8=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 9=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt()
tests.test_encoding/TestEncoding.test_base32
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> lc = Brandon(config) <del> lc = LanguageChecker.LanguageChecker()
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base32(self): <0> lc = LanguageChecker.LanguageChecker() <1> ep = EncodingParent(lc) <2> a = "NBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLF" <3> result = ep.decrypt(a) <4> self.assertEqual(result["IsPlaintext?"], True) <5>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent decrypt(text) at: ciphey.LanguageChecker.brandon Brandon(config: Dict[str, object]) at: tests.test_encoding config = {"wordlist": cipheydists.get_list("english"), "params": {}} at: tests.test_encoding.TestEncoding.test_morse ep = EncodingParent(lc) a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." at: unittest.case.TestCase assertEqual(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ from multiprocessing.dummy import Pool as ThreadPool pool = ThreadPool(4) answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] + if answer is not None and answer["IsPlaintext?"]: - if answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 1=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_ascii(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = "68 65 6C 6C 6F 20 64 6F 67" result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 2=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 3=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_morse(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 4=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 5=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): + def test_hex_mixed_spaces_yes(self): + lc = Brandon(config) + ep = EncodingParent(lc) + a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + a = a.replace(" ", "") + result = ep.decrypt(a) + self.assertEqual(result["IsPlaintext?"], True) + ===========changed ref 6=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 7=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_binary_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt( "01001000 01100101 01101100 01101100 01101111 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 01110011 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100 01110011" ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 8=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_hex_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) - a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" - a = a.replace(" ", "") + result = ep.decrypt( - result = ep.decrypt(a) + "68 65 6c 6c 6f 20 6f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 9=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } +
tests.test_main/test_argument_grep_true
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<add> result = main(make_default_config("It was the best of times, it was the worst of times")) <del> result = main(text="It was the best of times, it was the worst of times")
# module: tests.test_main def test_argument_grep_true(): <0> result = main(text="It was the best of times, it was the worst of times") <1> assert result == "It was the best of times, it was the worst of times" <2>
===========unchanged ref 0=========== at: ciphey.__main__ make_default_config(ctext: str) -> Dict[str, object] main(config: Dict[str, object]=None) -> Optional[str] ===========changed ref 0=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 1=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt() ===========changed ref 2=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 3=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 4=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_ascii(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = "68 65 6C 6C 6F 20 64 6F 67" result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 5=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 6=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base32(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = "NBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLF" result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 7=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_morse(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 8=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): + def test_hex_mixed_spaces_yes(self): + lc = Brandon(config) + ep = EncodingParent(lc) + a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + a = a.replace(" ", "") + result = ep.decrypt(a) + self.assertEqual(result["IsPlaintext?"], True) + ===========changed ref 9=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_binary_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt( "01001000 01100101 01101100 01101100 01101111 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 01110011 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100 01110011" ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 10=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_hex_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) - a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" - a = a.replace(" ", "") + result = ep.decrypt( - result = ep.decrypt(a) + "68 65 6c 6c 6f 20 6f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + ) self.assertEqual(result["IsPlaintext?"], True)
tests.test_main/test_main_base64_true
Modified
Ciphey~Ciphey
50b576e9bdde1743ba47ab3f8624c21f0a7ebba2
Tests now fail correctly
<0>:<del> result = main( <1>:<add> result = main(make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=")) <del> text="SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=", <2>:<del> greppable=True, <3>:<del> ) <5>:<del> result["Plaintext"] <6>:<add> result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." <del> == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay."
# module: tests.test_main def test_main_base64_true(): <0> result = main( <1> text="SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=", <2> greppable=True, <3> ) <4> assert ( <5> result["Plaintext"] <6> == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." <7> ) <8>
===========unchanged ref 0=========== at: ciphey.__main__ make_default_config(ctext: str) -> Dict[str, object] main(config: Dict[str, object]=None) -> Optional[str] ===========changed ref 0=========== # module: ciphey.__main__ + + + def make_default_config(ctext: str) -> Dict[str, object]: + from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon + import cipheydists + return { + "ctext": ctext, + "grep": False, + "info": False, + "debug": "WARNING", + "checker": brandon, + "wordlist": set(cipheydists.get_list("english")), + "params": {} + } + ===========changed ref 1=========== # module: ciphey.__main__ + def main(config: Dict[str, object] = None) -> Optional[str]: - def main(config: dict = None) -> Optional[str]: """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. """ # We must fill in the arguments if they are not provided if config is None: + config = arg_parsing() - args = arg_parsing() # Check if we errored out + if config is None: - if args is None: return None # Now we have working arguments, we can expand it and pass it to the Ciphey constructor + cipher_obj = Ciphey(config) - cipher_obj = Ciphey(args) return cipher_obj.decrypt() ===========changed ref 2=========== # module: tests.test_main def test_argument_grep_true(): + result = main(make_default_config("It was the best of times, it was the worst of times")) - result = main(text="It was the best of times, it was the worst of times") assert result == "It was the best of times, it was the worst of times" ===========changed ref 3=========== # module: tests.test_encoding logger.remove() + config = {"wordlist": cipheydists.get_list("english"), "params": {}} + ===========changed ref 4=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_english_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("eW91ciB0ZXh0") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 5=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_ascii(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = "68 65 6C 6C 6F 20 64 6F 67" result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 6=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base64_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt("SGVsbG8gSSBsaWtlIGRvZ3MgYW5kIGNhdHM=") self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 7=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base32(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = "NBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLF" result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 8=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_morse(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 9=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): + def test_hex_mixed_spaces_yes(self): + lc = Brandon(config) + ep = EncodingParent(lc) + a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + a = a.replace(" ", "") + result = ep.decrypt(a) + self.assertEqual(result["IsPlaintext?"], True) + ===========changed ref 10=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_binary_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) result = ep.decrypt( "01001000 01100101 01101100 01101100 01101111 00100000 01001001 00100000 01101100 01101001 01101011 01100101 00100000 01100100 01101111 01100111 01110011 00100000 01100001 01101110 01100100 00100000 01100011 01100001 01110100 01110011" ) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 11=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_hex_spaces_yes(self): + lc = Brandon(config) - lc = LanguageChecker.LanguageChecker() ep = EncodingParent(lc) - a = "68656c6c6f206f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" - a = a.replace(" ", "") + result = ep.decrypt( - result = ep.decrypt(a) + "68 65 6c 6c 6f 20 6f 6c 69 76 69 61 20 69 20 72 65 61 6c 6c 79 20 6c 69 6b 65 20 79 6f 75 72 20 64 6f 67" + ) self.assertEqual(result["IsPlaintext?"], True)
ciphey.__main__/Ciphey.__init__
Modified
Ciphey~Ciphey
77f4ffcd3ff28859f34038132e3b6b2f5714b8b3
Fixed brandon
<4>:<del> logger.trace(f"""Finished argument object is {config}""")
# module: ciphey.__main__ class Ciphey: def __init__(self, config): <0> logger.remove() <1> logger.configure() <2> logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) <3> logger.opt(colors=True) <4> logger.trace(f"""Finished argument object is {config}""") <5> logger.debug(f"""Debug level set to {config["debug"]}""") <6> # general purpose modules <7> self.ai = NeuralNetwork() <8> self.lc = config["checker"](config) <9> self.mh = mh.mathsHelper() <10> # the one bit of text given to us to decrypt <11> self.text: str = config["ctext"] <12> self.basic = BasicParent(self.lc) <13> self.hash = HashParent() <14> self.encoding = EncodingParent(self.lc) <15> self.level: int = 1 <16> self.greppable: bool = config["grep"] <17> self.cipher_info = config["info"] <18> self.console = Console() <19> self.probability_distribution: dict = {} <20> self.what_to_choose: dict = {} <21>
===========unchanged ref 0=========== at: Decryptor.Hash.hashParent HashParent() at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.basicEncryption.basic_parent BasicParent(lc) at: ciphey.__main__.Ciphey.decrypt self.probability_distribution: dict = self.ai.predictnn(self.text)[0] self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) at: ciphey.mathsHelper mathsHelper() at: neuralNetworkMod.nn NeuralNetwork() at: sys stderr: TextIO at: typing.IO __slots__ = () isatty() -> bool ===========changed ref 0=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent except ModuleNotFoundError: + from LanguageChecker import LanguageChecker as lc - from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh
tests.test_main/test_argument_grep_true
Modified
Ciphey~Ciphey
77f4ffcd3ff28859f34038132e3b6b2f5714b8b3
Fixed brandon
<0>:<add> cfg = make_default_config("It was the best of times, it was the worst of times") <del> result = main(make_default_config("It was the best of times, it was the worst of times")) <1>:<add> cfg["debug"] = "TRACE" <add> result = main(cfg)
# module: tests.test_main def test_argument_grep_true(): <0> result = main(make_default_config("It was the best of times, it was the worst of times")) <1> assert result == "It was the best of times, it was the worst of times" <2>
===========unchanged ref 0=========== at: ciphey.__main__ make_default_config(ctext: str) -> Dict[str, object] ===========changed ref 0=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent except ModuleNotFoundError: + from LanguageChecker import LanguageChecker as lc - from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: def __init__(self, config): logger.remove() logger.configure() logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) logger.opt(colors=True) - logger.trace(f"""Finished argument object is {config}""") logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {}
tests.test_main/test_main_base64_true
Modified
Ciphey~Ciphey
77f4ffcd3ff28859f34038132e3b6b2f5714b8b3
Fixed brandon
<0>:<add> cfg = make_default_config("It was the best of times, it was the worst of times") <add> cfg["debug"] = "TRACE" <add> result = main("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4") <del> result = main(make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4="))
# module: tests.test_main def test_main_base64_true(): <0> result = main(make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=")) <1> assert ( <2> result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." <3> ) <4>
===========unchanged ref 0=========== at: ciphey.__main__ make_default_config(ctext: str) -> Dict[str, object] ===========changed ref 0=========== # module: tests.test_main def test_argument_grep_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") - result = main(make_default_config("It was the best of times, it was the worst of times")) + cfg["debug"] = "TRACE" + result = main(cfg) assert result == "It was the best of times, it was the worst of times" ===========changed ref 1=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent except ModuleNotFoundError: + from LanguageChecker import LanguageChecker as lc - from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh ===========changed ref 2=========== # module: ciphey.__main__ class Ciphey: def __init__(self, config): logger.remove() logger.configure() logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) logger.opt(colors=True) - logger.trace(f"""Finished argument object is {config}""") logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {}
ciphey.LanguageChecker.brandon/Brandon.checkWordlist
Modified
Ciphey~Ciphey
77f4ffcd3ff28859f34038132e3b6b2f5714b8b3
Fixed brandon
<12>:<del> text: set = self.cleanText(text) <13>:<del> <14>:<add> return len(text.intersection(self.wordlist)) / len(text) <del> return len(text.intersection(self.wordlist)) // len(text)
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def checkWordlist(self, text: Set[str]) -> float: - def checkWordlist(self, text: str) -> float: <0> """Sorts & searches the dict, and returns the proportion of the words that are in the dictionary <1> <2> Args: <3> text -> The text we use to perform analysis on <4> language -> the language we want to check <5> <6> Returns: <7> counter -> how many words in text, are in the dict of language <8> <9> """ <10> # reads through most common words / passwords <11> # and calculates how much of that is in language <12> text: set = self.cleanText(text) <13> <14> return len(text.intersection(self.wordlist)) // len(text) <15>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon.Brandon wordlist: set at: ciphey.LanguageChecker.brandon.Brandon.__init__ self.wordlist = config["wordlist"] at: typing Set = _alias(set, 1, inst=False, name='Set') ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): """ Class designed to confirm whether something is **language** based on how many words of **language** appears Call confirmLanguage(text, language) * text: the text you want to confirm * language: the language you want to confirm Find out what language it is by using chisquared.py, the highest chisquared score is the language languageThreshold = 45 if a string is 45% **language** words, then it's confirmed to be english """ + + wordlist: set ===========changed ref 1=========== # module: tests.test_main def test_argument_grep_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") - result = main(make_default_config("It was the best of times, it was the worst of times")) + cfg["debug"] = "TRACE" + result = main(cfg) assert result == "It was the best of times, it was the worst of times" ===========changed ref 2=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent except ModuleNotFoundError: + from LanguageChecker import LanguageChecker as lc - from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh ===========changed ref 3=========== # module: ciphey.__main__ class Ciphey: def __init__(self, config): logger.remove() logger.configure() logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) logger.opt(colors=True) - logger.trace(f"""Finished argument object is {config}""") logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 4=========== # module: tests.test_main def test_main_base64_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") + cfg["debug"] = "TRACE" + result = main("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4") - result = main(make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=")) assert ( result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." )
ciphey.LanguageChecker.brandon/Brandon.check1000Words
Modified
Ciphey~Ciphey
77f4ffcd3ff28859f34038132e3b6b2f5714b8b3
Fixed brandon
<17>:<del> logger.trace(f"text before cleaning is {text}") <18>:<del> text = self.cleanText(text) <19>:<del> logger.trace(f"Check 1000 words text is {text}")
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def check1000Words(self, text: Set[str]) -> bool: - def check1000Words(self, text: str) -> bool: <0> """Checks to see if word is in the list of 1000 words <1> <2> the 1000words is a dict, so lookup is O(1) <3> <4> Args: <5> text -> The text we use to text (a word) <6> <7> Returns: <8> bool -> whether it's in the dict or not. <9> <10> """ <11> # If we have no wordlist, then we can't reject the candidate on this basis <12> if self.top1000Words is None: <13> return True <14> <15> if text is None: <16> return False <17> logger.trace(f"text before cleaning is {text}") <18> text = self.cleanText(text) <19> logger.trace(f"Check 1000 words text is {text}") <20> # If any of the top 1000 words in the text appear <21> # return true <22> for word in text: <23> # I was debating using any() here, but I think they're the <24> # same speed so it doesn't really matter too much <25> if word in self.top1000Words: <26> return True <27> return False <28>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon.Brandon.__init__ self.top1000Words = config["params"].get("top1000") at: typing Set = _alias(set, 1, inst=False, name='Set') ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def checkWordlist(self, text: Set[str]) -> float: - def checkWordlist(self, text: str) -> float: """Sorts & searches the dict, and returns the proportion of the words that are in the dictionary Args: text -> The text we use to perform analysis on language -> the language we want to check Returns: counter -> how many words in text, are in the dict of language """ # reads through most common words / passwords # and calculates how much of that is in language - text: set = self.cleanText(text) - + return len(text.intersection(self.wordlist)) / len(text) - return len(text.intersection(self.wordlist)) // len(text) ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): """ Class designed to confirm whether something is **language** based on how many words of **language** appears Call confirmLanguage(text, language) * text: the text you want to confirm * language: the language you want to confirm Find out what language it is by using chisquared.py, the highest chisquared score is the language languageThreshold = 45 if a string is 45% **language** words, then it's confirmed to be english """ + + wordlist: set ===========changed ref 2=========== # module: tests.test_main def test_argument_grep_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") - result = main(make_default_config("It was the best of times, it was the worst of times")) + cfg["debug"] = "TRACE" + result = main(cfg) assert result == "It was the best of times, it was the worst of times" ===========changed ref 3=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent except ModuleNotFoundError: + from LanguageChecker import LanguageChecker as lc - from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh ===========changed ref 4=========== # module: ciphey.__main__ class Ciphey: def __init__(self, config): logger.remove() logger.configure() logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) logger.opt(colors=True) - logger.trace(f"""Finished argument object is {config}""") logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 5=========== # module: tests.test_main def test_main_base64_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") + cfg["debug"] = "TRACE" + result = main("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4") - result = main(make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=")) assert ( result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." )
ciphey.LanguageChecker.brandon/Brandon.confirmLanguage
Modified
Ciphey~Ciphey
77f4ffcd3ff28859f34038132e3b6b2f5714b8b3
Fixed brandon
<15>:<del> logger.trace( <16>:<add> logger.trace(f"The language proportion {proportion} is over the threshold {self.languageThreshold}") <del> f"The language proportion {proportion} is over the threshold {self.languageThreshold}" <17>:<del> ) <20>:<add> logger.trace(f"The language proportion {proportion} is under the threshold {self.languageThreshold}")
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def confirmLanguage(self, text: set) -> True: - def confirmLanguage(self, text: str) -> True: <0> """Confirms whether given text is language <1> <2> If the proportion (taken from checkDictionary) is higher than the language threshold, return True <3> <4> Args: <5> text -> The text we use to text (a word) <6> language -> the language we use to check <7> <8> Returns: <9> bool -> whether it's written in Language or not <10> <11> """ <12> <13> proportion = self.checkWordlist(text) <14> if self.checkWordlist(text) >= self.languageThreshold: <15> logger.trace( <16> f"The language proportion {proportion} is over the threshold {self.languageThreshold}" <17> ) <18> return True <19> else: <20> return False <21>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon.Brandon checkWordlist(self, text: Set[str]) -> float checkWordlist(text: Set[str]) -> float at: ciphey.LanguageChecker.brandon.Brandon.__init__ self.languageThreshold = config["params"].get("threshold", 0.55) at: ciphey.LanguageChecker.iface.LanguageChecker __init__(self, config: Dict[str, object]) __init__(config: Dict[str, object]) ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def checkWordlist(self, text: Set[str]) -> float: - def checkWordlist(self, text: str) -> float: """Sorts & searches the dict, and returns the proportion of the words that are in the dictionary Args: text -> The text we use to perform analysis on language -> the language we want to check Returns: counter -> how many words in text, are in the dict of language """ # reads through most common words / passwords # and calculates how much of that is in language - text: set = self.cleanText(text) - + return len(text.intersection(self.wordlist)) / len(text) - return len(text.intersection(self.wordlist)) // len(text) ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): """ Class designed to confirm whether something is **language** based on how many words of **language** appears Call confirmLanguage(text, language) * text: the text you want to confirm * language: the language you want to confirm Find out what language it is by using chisquared.py, the highest chisquared score is the language languageThreshold = 45 if a string is 45% **language** words, then it's confirmed to be english """ + + wordlist: set ===========changed ref 2=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def check1000Words(self, text: Set[str]) -> bool: - def check1000Words(self, text: str) -> bool: """Checks to see if word is in the list of 1000 words the 1000words is a dict, so lookup is O(1) Args: text -> The text we use to text (a word) Returns: bool -> whether it's in the dict or not. """ # If we have no wordlist, then we can't reject the candidate on this basis if self.top1000Words is None: return True if text is None: return False - logger.trace(f"text before cleaning is {text}") - text = self.cleanText(text) - logger.trace(f"Check 1000 words text is {text}") # If any of the top 1000 words in the text appear # return true for word in text: # I was debating using any() here, but I think they're the # same speed so it doesn't really matter too much if word in self.top1000Words: return True return False ===========changed ref 3=========== # module: tests.test_main def test_argument_grep_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") - result = main(make_default_config("It was the best of times, it was the worst of times")) + cfg["debug"] = "TRACE" + result = main(cfg) assert result == "It was the best of times, it was the worst of times" ===========changed ref 4=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent except ModuleNotFoundError: + from LanguageChecker import LanguageChecker as lc - from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh ===========changed ref 5=========== # module: ciphey.__main__ class Ciphey: def __init__(self, config): logger.remove() logger.configure() logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) logger.opt(colors=True) - logger.trace(f"""Finished argument object is {config}""") logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {} ===========changed ref 6=========== # module: tests.test_main def test_main_base64_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") + cfg["debug"] = "TRACE" + result = main("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4") - result = main(make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=")) assert ( result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." )
ciphey.LanguageChecker.brandon/Brandon.checkLanguage
Modified
Ciphey~Ciphey
77f4ffcd3ff28859f34038132e3b6b2f5714b8b3
Fixed brandon
<11>:<add> logger.trace(f"In Language Checker with \"{text}\"") <del> logger.trace(f"In Language Checker with {text}") <12>:<add> text = self.cleanText(text) <add> logger.trace(f"Text split to \"{text}\"") <23>:<add> if not self.confirmLanguage(text): <del> result2: bool = self.confirmLanguage(text) <24>:<del> if not result2:
# module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): def checkLanguage(self, text: str) -> bool: <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> if text == "": <13> return False <14> if not self.check1000Words(text): <15> logger.debug( <16> f"1000 words failed. This is not plaintext" <17> ) <18> return False <19> <20> logger.trace( <21> f"1000words check passed" <22> ) <23> result2: bool = self.confirmLanguage(text) <24> if not result2: <25> logger.debug(f"Dictionary check failed. This is not plaintext") <26> return False <27> <28> logger.trace(f"Dictionary check passed. This is plaintext") <29> return True <30>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon.Brandon cleanText(text: str) -> set check1000Words(text: Set[str]) -> bool check1000Words(self, text: Set[str]) -> bool confirmLanguage(text: set) -> True confirmLanguage(self, text: set) -> True at: ciphey.LanguageChecker.iface.LanguageChecker getArgs(**kwargs) -> Dict[str, object] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def confirmLanguage(self, text: set) -> True: - def confirmLanguage(self, text: str) -> True: """Confirms whether given text is language If the proportion (taken from checkDictionary) is higher than the language threshold, return True Args: text -> The text we use to text (a word) language -> the language we use to check Returns: bool -> whether it's written in Language or not """ proportion = self.checkWordlist(text) if self.checkWordlist(text) >= self.languageThreshold: - logger.trace( + logger.trace(f"The language proportion {proportion} is over the threshold {self.languageThreshold}") - f"The language proportion {proportion} is over the threshold {self.languageThreshold}" - ) return True else: + logger.trace(f"The language proportion {proportion} is under the threshold {self.languageThreshold}") return False ===========changed ref 1=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def check1000Words(self, text: Set[str]) -> bool: - def check1000Words(self, text: str) -> bool: """Checks to see if word is in the list of 1000 words the 1000words is a dict, so lookup is O(1) Args: text -> The text we use to text (a word) Returns: bool -> whether it's in the dict or not. """ # If we have no wordlist, then we can't reject the candidate on this basis if self.top1000Words is None: return True if text is None: return False - logger.trace(f"text before cleaning is {text}") - text = self.cleanText(text) - logger.trace(f"Check 1000 words text is {text}") # If any of the top 1000 words in the text appear # return true for word in text: # I was debating using any() here, but I think they're the # same speed so it doesn't really matter too much if word in self.top1000Words: return True return False ===========changed ref 2=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): + def checkWordlist(self, text: Set[str]) -> float: - def checkWordlist(self, text: str) -> float: """Sorts & searches the dict, and returns the proportion of the words that are in the dictionary Args: text -> The text we use to perform analysis on language -> the language we want to check Returns: counter -> how many words in text, are in the dict of language """ # reads through most common words / passwords # and calculates how much of that is in language - text: set = self.cleanText(text) - + return len(text.intersection(self.wordlist)) / len(text) - return len(text.intersection(self.wordlist)) // len(text) ===========changed ref 3=========== # module: ciphey.LanguageChecker.brandon class Brandon(LanguageChecker): """ Class designed to confirm whether something is **language** based on how many words of **language** appears Call confirmLanguage(text, language) * text: the text you want to confirm * language: the language you want to confirm Find out what language it is by using chisquared.py, the highest chisquared score is the language languageThreshold = 45 if a string is 45% **language** words, then it's confirmed to be english """ + + wordlist: set ===========changed ref 4=========== # module: tests.test_main def test_argument_grep_true(): + cfg = make_default_config("It was the best of times, it was the worst of times") - result = main(make_default_config("It was the best of times, it was the worst of times")) + cfg["debug"] = "TRACE" + result = main(cfg) assert result == "It was the best of times, it was the worst of times" ===========changed ref 5=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent except ModuleNotFoundError: + from LanguageChecker import LanguageChecker as lc - from languageCheckerMod import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent try: import mathsHelper as mh except ModuleNotFoundError: import ciphey.mathsHelper as mh ===========changed ref 6=========== # module: ciphey.__main__ class Ciphey: def __init__(self, config): logger.remove() logger.configure() logger.add(sink=sys.stderr, level=config["debug"], colorize=sys.stderr.isatty()) logger.opt(colors=True) - logger.trace(f"""Finished argument object is {config}""") logger.debug(f"""Debug level set to {config["debug"]}""") # general purpose modules self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() # the one bit of text given to us to decrypt self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.cipher_info = config["info"] self.console = Console() self.probability_distribution: dict = {} self.what_to_choose: dict = {}
ciphey.__main__/make_default_config
Modified
Ciphey~Ciphey
c0bc687f14a4efd827a8e523e4bff15132e39eb1
Fixed tests and such like
<6>:<add> "debug": "TRACE" if trace else "WARNING", <del> "debug": "WARNING",
# module: ciphey.__main__ + def make_default_config(ctext: str, trace: bool = False) -> Dict[str, object]: - def make_default_config(ctext: str) -> Dict[str, object]: <0> from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon <1> import cipheydists <2> return { <3> "ctext": ctext, <4> "grep": False, <5> "info": False, <6> "debug": "WARNING", <7> "checker": brandon, <8> "wordlist": set(cipheydists.get_list("english")), <9> "params": {} <10> } <11>
===========unchanged ref 0=========== at: ciphey.LanguageChecker.brandon ciphey_language_checker = Brandon at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
tests.test_encoding/TestEncoding.test_base32
Modified
Ciphey~Ciphey
c0bc687f14a4efd827a8e523e4bff15132e39eb1
Fixed tests and such like
<0>:<add> logger.remove() <add> logger.configure() <add> logger.add(sink=sys.stderr, level="TRACE", colorize=True) <add> logger.opt(colors=True) <add> logger.error(f"""Debug level set to {config["debug"]}""") <add>
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base32(self): <0> lc = Brandon(config) <1> ep = EncodingParent(lc) <2> a = "NBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLF" <3> result = ep.decrypt(a) <4> self.assertEqual(result["IsPlaintext?"], True) <5>
===========unchanged ref 0=========== at: sys stderr: TextIO at: tests.test_encoding config = make_default_config("") ===========changed ref 0=========== # module: tests.test_encoding - logger.remove() - config = make_default_config("") ===========changed ref 1=========== # module: ciphey.__main__ + def make_default_config(ctext: str, trace: bool = False) -> Dict[str, object]: - def make_default_config(ctext: str) -> Dict[str, object]: from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon import cipheydists return { "ctext": ctext, "grep": False, "info": False, + "debug": "TRACE" if trace else "WARNING", - "debug": "WARNING", "checker": brandon, "wordlist": set(cipheydists.get_list("english")), "params": {} }
tests.test_main/test_main_base64_true
Modified
Ciphey~Ciphey
c0bc687f14a4efd827a8e523e4bff15132e39eb1
Fixed tests and such like
<0>:<add> cfg = make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=") <del> cfg = make_default_config("It was the best of times, it was the worst of times") <2>:<add> result = main(cfg) <del> result = main("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4")
# module: tests.test_main def test_main_base64_true(): <0> cfg = make_default_config("It was the best of times, it was the worst of times") <1> cfg["debug"] = "TRACE" <2> result = main("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4") <3> assert ( <4> result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." <5> ) <6>
===========unchanged ref 0=========== at: ciphey.__main__ make_default_config(ctext: str, trace: bool=False) -> Dict[str, object] main(config: Dict[str, object]=None) -> Optional[str] ===========changed ref 0=========== # module: ciphey.__main__ + def make_default_config(ctext: str, trace: bool = False) -> Dict[str, object]: - def make_default_config(ctext: str) -> Dict[str, object]: from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon import cipheydists return { "ctext": ctext, "grep": False, "info": False, + "debug": "TRACE" if trace else "WARNING", - "debug": "WARNING", "checker": brandon, "wordlist": set(cipheydists.get_list("english")), "params": {} } ===========changed ref 1=========== # module: tests.test_encoding - logger.remove() - config = make_default_config("") ===========changed ref 2=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base32(self): + logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level="TRACE", colorize=True) + logger.opt(colors=True) + logger.error(f"""Debug level set to {config["debug"]}""") + lc = Brandon(config) ep = EncodingParent(lc) a = "NBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLF" result = ep.decrypt(a) self.assertEqual(result["IsPlaintext?"], True)
ciphey.Decryptor.Encoding.bases/Bases._dispatch
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<18>:<add> return self.goodRet(result, cipher=cipher) <del> return self.goodRet(result, cipher="Bases")
# module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): <0> logger.trace("Attempting base64") <1> result = None <2> try: <3> result = decoder(text) <4> # yeet turning b strings into normal stringy bois <5> result = result.decode("utf-8") <6> except UnicodeDecodeError as e: <7> logger.trace("Bad unicode") <8> result = None <9> except binascii.Error as e: <10> logger.trace("binascii error") <11> result = None <12> except ValueError: <13> logger.trace("Failed to decode base") <14> result = None <15> <16> if result is not None and self.lc.checkLanguage(result): <17> logger.debug(f"Bases successful, returning {result}") <18> return self.goodRet(result, cipher="Bases") <19> else: <20> return self.badRet() <21>
===========unchanged ref 0=========== at: binascii Error(*args: object) at: ciphey.Decryptor.Encoding.bases.Bases goodRet(result, cipher) badRet() at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc at: ciphey.LanguageChecker.brandon.Brandon wordlist: set checkLanguage(text: str) -> bool at: typing Callable = _CallableType(collections.abc.Callable, 2)
ciphey.Decryptor.Encoding.bases/Bases.base64
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<8>:<add> return self._dispatch(base64.b64decode, text, "base64") <del> return self._dispatch(base64.b64decode, text)
# module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): <0> """Base64 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base64 <6> """ <7> logger.trace("Attempting base64") <8> return self._dispatch(base64.b64decode, text) <9>
===========unchanged ref 0=========== at: base64 b64decode(s: _decodable, altchars: Optional[bytes]=..., validate: bool=...) -> bytes at: ciphey.Decryptor.Encoding.bases.Bases _dispatch(decoder: Callable[[str], bytes], text: str, cipher: str) _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet()
ciphey.Decryptor.Encoding.bases/Bases.base32
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<8>:<add> return self._dispatch(base64.b32decode, text, "base32") <del> return self._dispatch(base64.b32decode, text)
# module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): <0> """Base32 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base32 <6> """ <7> logger.trace("Attempting base32") <8> return self._dispatch(base64.b32decode, text) <9>
===========unchanged ref 0=========== at: base64 b32decode(s: _decodable, casefold: bool=..., map01: Optional[bytes]=...) -> bytes at: ciphey.Decryptor.Encoding.bases.Bases _dispatch(decoder: Callable[[str], bytes], text: str, cipher: str) _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet() ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): """Base64 decode args: text -> text to decode returns: the text decoded as base64 """ logger.trace("Attempting base64") + return self._dispatch(base64.b64decode, text, "base64") - return self._dispatch(base64.b64decode, text)
ciphey.Decryptor.Encoding.bases/Bases.base16
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<8>:<add> return self._dispatch(base64.b16decode, text, "base16") <del> return self._dispatch(base64.b16decode, text)
# module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text: str): <0> """Base16 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base16 <6> """ <7> logger.trace("Attempting base16") <8> return self._dispatch(base64.b16decode, text) <9>
===========unchanged ref 0=========== at: base64 b16decode(s: _decodable, casefold: bool=...) -> bytes at: ciphey.Decryptor.Encoding.bases.Bases _dispatch(decoder: Callable[[str], bytes], text: str, cipher: str) _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet() ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ logger.trace("Attempting base32") + return self._dispatch(base64.b32decode, text, "base32") - return self._dispatch(base64.b32decode, text) ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): """Base64 decode args: text -> text to decode returns: the text decoded as base64 """ logger.trace("Attempting base64") + return self._dispatch(base64.b64decode, text, "base64") - return self._dispatch(base64.b64decode, text)
ciphey.Decryptor.Encoding.bases/Bases.base85
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<9>:<add> return self._dispatch(base64.b85decode, text, "base85") <del> return self._dispatch(base64.b85decode, text)
# module: ciphey.Decryptor.Encoding.bases class Bases: def base85(self, text: str): <0> """Base85 decode <1> <2> args: <3> text -> text to decode <4> returns: <5> the text decoded as base85 <6> """ <7> logger.trace("Attempting base85") <8> result = None <9> return self._dispatch(base64.b85decode, text) <10>
===========unchanged ref 0=========== at: base64 b85decode(b: _decodable) -> bytes at: ciphey.Decryptor.Encoding.bases.Bases _dispatch(decoder: Callable[[str], bytes], text: str, cipher: str) _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet() ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text: str): """Base16 decode args: text -> text to decode returns: the text decoded as base16 """ logger.trace("Attempting base16") + return self._dispatch(base64.b16decode, text, "base16") - return self._dispatch(base64.b16decode, text) ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ logger.trace("Attempting base32") + return self._dispatch(base64.b32decode, text, "base32") - return self._dispatch(base64.b32decode, text) ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): """Base64 decode args: text -> text to decode returns: the text decoded as base64 """ logger.trace("Attempting base64") + return self._dispatch(base64.b64decode, text, "base64") - return self._dispatch(base64.b64decode, text)
ciphey.Decryptor.Encoding.encodingParent/EncodingParent.decrypt
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<10>:<add> # from multiprocessing.dummy import Pool as ThreadPool <del> from multiprocessing.dummy import Pool as ThreadPool <12>:<add> # pool = ThreadPool(4) <del> pool = ThreadPool(4) <13>:<add> # answers = pool.map(self.callDecrypt, torun) # It's not worth the thread overhead <add> answers = map(self.callDecrypt, torun) <del> answers = pool.map(self.callDecrypt, torun)
# module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): <0> self.text = text <1> torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] <2> logger.debug(f"Encoding parent is running {torun}") <3> """ <4> ok so I have an array of functions <5> and I want to apply each function to some text <6> (text, function) <7> but the way it works is you apply text to every item in the array (function) <8> <9> """ <10> from multiprocessing.dummy import Pool as ThreadPool <11> <12> pool = ThreadPool(4) <13> answers = pool.map(self.callDecrypt, torun) <14> <15> for answer in answers: <16> logger.debug(f"All answers are {answers}") <17> # adds the LC objects together <18> # self.lc = self.lc + answer["lc"] <19> if answer is not None and answer["IsPlaintext?"]: <20> logger.debug(f"Plaintext found {answer}") <21> return answer <22> return { <23> "lc": self.lc, <24> "IsPlaintext?": False, <25> "Plaintext": None, <26> "Cipher": None, <27> "Extra Information": None, <28> } <29>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent callDecrypt(obj) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent.__init__ self.lc = lc self.base64 = Bases(self.lc) self.binary = Binary(self.lc) self.hex = Hexadecimal(self.lc) self.ascii = Ascii(self.lc) self.morse = MorseCode(self.lc) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text: str): """Base16 decode args: text -> text to decode returns: the text decoded as base16 """ logger.trace("Attempting base16") + return self._dispatch(base64.b16decode, text, "base16") - return self._dispatch(base64.b16decode, text) ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ logger.trace("Attempting base32") + return self._dispatch(base64.b32decode, text, "base32") - return self._dispatch(base64.b32decode, text) ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): """Base64 decode args: text -> text to decode returns: the text decoded as base64 """ logger.trace("Attempting base64") + return self._dispatch(base64.b64decode, text, "base64") - return self._dispatch(base64.b64decode, text) ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base85(self, text: str): """Base85 decode args: text -> text to decode returns: the text decoded as base85 """ logger.trace("Attempting base85") result = None + return self._dispatch(base64.b85decode, text, "base85") - return self._dispatch(base64.b85decode, text) ===========changed ref 4=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet()
ciphey.__main__/Ciphey.decrypt
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<16>:<add> return { <del> return self.text <17>:<add> "lc": self.lc, <add> "IsPlaintext?": True, <add> "Plaintext": self.text, <add> "Cipher": None, <add> "Extra Information": None, <add> }
# module: ciphey.__main__ class Ciphey: + def decrypt(self) -> Optional[Dict]: - def decrypt(self): <0> """Performs the decryption of text <1> <2> Creates the probability table, calls one_level_of_decryption <3> <4> Args: <5> None, it uses class variables. <6> <7> Returns: <8> None <9> """ <10> # Read the documentation for more on this function. <11> # checks to see if inputted text is plaintext <12> result = self.lc.checkLanguage(self.text) <13> if result: <14> print("You inputted plain text!") <15> print(f"Returning {self.text}") <16> return self.text <17> self.probability_distribution: dict = self.ai.predictnn(self.text)[0] <18> self.what_to_choose: dict = { <19> self.hash: { <20> "sha1": self.probability_distribution[0], <21> "md5": self.probability_distribution[1], <22> "sha256": self.probability_distribution[2], <23> "sha512": self.probability_distribution[3], <24> }, <25> self.basic: {"caesar": self.probability_distribution[4]}, <26> "plaintext": {"plaintext": self.probability_distribution[5]}, <27> self.encoding: { <28> "reverse": self.probability_distribution[6], <29> "base64": self.probability_distribution[7], <30> "binary": self.probability_distribution[8], <31> "hexadecimal": self.probability_distribution[9], <32> "ascii": self.probability_distribution[10], <33> "morse": self.probability_distribution[11], <34> }, <35> } <36> <37> logger.trace( <38> f"The probability table before 0.1 in __main__ is {self.what_to_choose}" </s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: + def decrypt(self) -> Optional[Dict]: - def decrypt(self): # offset: 1 # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. if v < 0.01: self.what_to_choose[key][k] = 0.01 logger.trace( f"The probability table after 0.1 in __main__ is {self.what_to_choose}" ) self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) # Creates and prints the probability table if not self.greppable: self.produceprobtable(self.what_to_choose) logger.debug( f"The new probability table after sorting in __main__ is {self.what_to_choose}" ) """ #for each dictionary in the dictionary # sort that dictionary #sort the overall dictionary by the first value of the new dictionary """ output = None if self.level <= 1: output = self.one_level_of_decryption() else: # TODO: make tmpfile f = open("decryptionContents.txt", "w") output = self.one_level_of_decryption(file=f) for i in range(0, self.level): # open file and go through each text item pass logger.debug(f"decrypt is outputting {output}") return output ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey config = dict() params = dict() produceprobtable(prob_table) -> None one_level_of_decryption() -> Optional[dict] at: ciphey.__main__.Ciphey.__init__ self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.probability_distribution: dict = {} self.what_to_choose: dict = {} at: ciphey.neuralNetworkMod.nn.NeuralNetwork predictnn(text) at: mathsHelper.mathsHelper sort_prob_table(prob_table: dict) -> dict ===========changed ref 0=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent + import ciphey.mathsHelper as mh except ModuleNotFoundError: from LanguageChecker import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent - - - try: import mathsHelper as mh - except ModuleNotFoundError: - import ciphey.mathsHelper as mh ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text: str): """Base16 decode args: text -> text to decode returns: the text decoded as base16 """ logger.trace("Attempting base16") + return self._dispatch(base64.b16decode, text, "base16") - return self._dispatch(base64.b16decode, text) ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ logger.trace("Attempting base32") + return self._dispatch(base64.b32decode, text, "base32") - return self._dispatch(base64.b32decode, text) ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): """Base64 decode args: text -> text to decode returns: the text decoded as base64 """ logger.trace("Attempting base64") + return self._dispatch(base64.b64decode, text, "base64") - return self._dispatch(base64.b64decode, text) ===========changed ref 4=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base85(self, text: str): """Base85 decode args: text -> text to decode returns: the text decoded as base85 """ logger.trace("Attempting base85") result = None + return self._dispatch(base64.b85decode, text, "base85") - return self._dispatch(base64.b85decode, text) ===========changed ref 5=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet()
ciphey.__main__/Ciphey.decrypt_normal
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<11>:<add> # This is redundant <add> # result = self.lc.checkLanguage(self.text) <del> result = self.lc.checkLanguage(self.text) <12>:<add> # if result: <del> if result: <13>:<add> # print("You inputted plain text!") <del> print("You inputted plain text!") <14>:<add> # print(f"Returning {self.text}") <del> print(f"Returning {self.text}") <15>:<add> # return self.text <del> return self.text
# module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[dict]: - def decrypt_normal(self, bar=None) -> Optional[str]: <0> """Called by one_level_of_decryption <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> bar -> whether or not to use alive_Bar <6> <7> Returns: <8> str if found, or None if not <9> <10> """ <11> result = self.lc.checkLanguage(self.text) <12> if result: <13> print("You inputted plain text!") <14> print(f"Returning {self.text}") <15> return self.text <16> <17> logger.debug(f"In decrypt_normal") <18> for key, val in self.what_to_choose.items(): <19> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <20> if not isinstance(key, str): <21> key.setProbTable(val) <22> ret: dict = key.decrypt(self.text) <23> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <24> logger.debug( <25> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <26> ) <27> <28> if ret["IsPlaintext?"]: <29> logger.debug(f"Ret is plaintext") <30> print(ret["Plaintext"]) <31> if self.cipher_info: <32> if ret["Extra Information"] is not None: <33> print( <34> "The cipher used is", <35> ret["Cipher"] + ".", <36> ret["Extra Information"] + ".", <37> ) <38> else: <39> print("</s>
===========below chunk 0=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[dict]: - def decrypt_normal(self, bar=None) -> Optional[str]: # offset: 1 return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey.__init__ self.text: str = config["ctext"] self.cipher_info = config["info"] self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) at: ciphey.__main__.Ciphey.one_level_of_decryption output = self.decrypt_normal() output = None ===========changed ref 0=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent + import ciphey.mathsHelper as mh except ModuleNotFoundError: from LanguageChecker import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent - - - try: import mathsHelper as mh - except ModuleNotFoundError: - import ciphey.mathsHelper as mh ===========changed ref 1=========== # module: ciphey.__main__ class Ciphey: + def decrypt(self) -> Optional[Dict]: - def decrypt(self): """Performs the decryption of text Creates the probability table, calls one_level_of_decryption Args: None, it uses class variables. Returns: None """ # Read the documentation for more on this function. # checks to see if inputted text is plaintext result = self.lc.checkLanguage(self.text) if result: print("You inputted plain text!") print(f"Returning {self.text}") + return { - return self.text + "lc": self.lc, + "IsPlaintext?": True, + "Plaintext": self.text, + "Cipher": None, + "Extra Information": None, + } self.probability_distribution: dict = self.ai.predictnn(self.text)[0] self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } logger.trace(</s> ===========changed ref 2=========== # module: ciphey.__main__ class Ciphey: + def decrypt(self) -> Optional[Dict]: - def decrypt(self): # offset: 1 <s> "morse": self.probability_distribution[11], }, } logger.trace( f"The probability table before 0.1 in __main__ is {self.what_to_choose}" ) # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. if v < 0.01: self.what_to_choose[key][k] = 0.01 logger.trace( f"The probability table after 0.1 in __main__ is {self.what_to_choose}" ) self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) # Creates and prints the probability table if not self.greppable: self.produceprobtable(self.what_to_choose) logger.debug( f"The new probability table after sorting in __main__ is {self.what_to_choose}" ) """ #for each dictionary in the dictionary # sort that dictionary #sort the overall dictionary by the first value of the new dictionary """ output = None if self.level <= 1: output = self.one_level_of_decryption() else: # TODO: make tmpfile f = open("decryptionContents.txt", "w") output = self.one_level_of_decryption(file=f</s>
tests.test_main/test_argument_grep_true
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<3>:<add> assert result["Plaintext"] == "It was the best of times, it was the worst of times" <del> assert result == "It was the best of times, it was the worst of times"
# module: tests.test_main def test_argument_grep_true(): <0> cfg = make_default_config("It was the best of times, it was the worst of times") <1> cfg["debug"] = "TRACE" <2> result = main(cfg) <3> assert result == "It was the best of times, it was the worst of times" <4>
===========unchanged ref 0=========== at: ciphey.__main__ make_default_config(ctext: str, trace: bool=False) -> Dict[str, object] main(config: Dict[str, object]=None) -> Optional[str] ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text: str): """Base16 decode args: text -> text to decode returns: the text decoded as base16 """ logger.trace("Attempting base16") + return self._dispatch(base64.b16decode, text, "base16") - return self._dispatch(base64.b16decode, text) ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ logger.trace("Attempting base32") + return self._dispatch(base64.b32decode, text, "base32") - return self._dispatch(base64.b32decode, text) ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): """Base64 decode args: text -> text to decode returns: the text decoded as base64 """ logger.trace("Attempting base64") + return self._dispatch(base64.b64decode, text, "base64") - return self._dispatch(base64.b64decode, text) ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base85(self, text: str): """Base85 decode args: text -> text to decode returns: the text decoded as base85 """ logger.trace("Attempting base85") result = None + return self._dispatch(base64.b85decode, text, "base85") - return self._dispatch(base64.b85decode, text) ===========changed ref 4=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet() ===========changed ref 5=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent + import ciphey.mathsHelper as mh except ModuleNotFoundError: from LanguageChecker import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent - - - try: import mathsHelper as mh - except ModuleNotFoundError: - import ciphey.mathsHelper as mh ===========changed ref 6=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ + # from multiprocessing.dummy import Pool as ThreadPool - from multiprocessing.dummy import Pool as ThreadPool + # pool = ThreadPool(4) - pool = ThreadPool(4) + # answers = pool.map(self.callDecrypt, torun) # It's not worth the thread overhead + answers = map(self.callDecrypt, torun) - answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] if answer is not None and answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, } ===========changed ref 7=========== # module: ciphey.__main__ class Ciphey: + def decrypt_normal(self, bar=None) -> Optional[dict]: - def decrypt_normal(self, bar=None) -> Optional[str]: """Called by one_level_of_decryption Performs a decryption, but mainly parses the internal data packet and prints useful information. Args: bar -> whether or not to use alive_Bar Returns: str if found, or None if not """ + # This is redundant + # result = self.lc.checkLanguage(self.text) - result = self.lc.checkLanguage(self.text) + # if result: - if result: + # print("You inputted plain text!") - print("You inputted plain text!") + # print(f"Returning {self.text}") - print(f"Returning {self.text}") + # return self.text - return self.text logger.debug(f"In decrypt_normal") for key, val in self.what_to_choose.items(): # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string if not isinstance(key, str): key.setProbTable(val) ret: dict = key.decrypt(self.text) logger.debug(f"Decrypt normal in __main__ ret is {ret}") logger.debug( f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" ) if ret["IsPlaintext?"]: logger.debug(f"Ret is plaintext") print(ret["Plaintext"]) if self.cipher_info: if ret["Extra Information"] is not None: print( </s>
tests.test_main/test_main_base64_true
Modified
Ciphey~Ciphey
702a357237092d677ae8287d0f73cbe713984438
It works now
<4>:<add> result["Plaintext"] == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." <del> result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay."
# module: tests.test_main def test_main_base64_true(): <0> cfg = make_default_config("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLiBUaGVyZSBpcyBvbmx5IHNvIG11Y2ggcm9hZCBpbiBEb3ZlciBvbmUgY2FuIGxheS4=") <1> cfg["debug"] = "TRACE" <2> result = main(cfg) <3> assert ( <4> result == "It was the best of times, it was the worst of times. There is only so much road in Dover one can lay." <5> ) <6>
===========unchanged ref 0=========== at: ciphey.__main__ make_default_config(ctext: str, trace: bool=False) -> Dict[str, object] main(config: Dict[str, object]=None) -> Optional[str] ===========changed ref 0=========== # module: tests.test_main def test_argument_grep_true(): cfg = make_default_config("It was the best of times, it was the worst of times") cfg["debug"] = "TRACE" result = main(cfg) + assert result["Plaintext"] == "It was the best of times, it was the worst of times" - assert result == "It was the best of times, it was the worst of times" ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base16(self, text: str): """Base16 decode args: text -> text to decode returns: the text decoded as base16 """ logger.trace("Attempting base16") + return self._dispatch(base64.b16decode, text, "base16") - return self._dispatch(base64.b16decode, text) ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base32(self, text: str): """Base32 decode args: text -> text to decode returns: the text decoded as base32 """ logger.trace("Attempting base32") + return self._dispatch(base64.b32decode, text, "base32") - return self._dispatch(base64.b32decode, text) ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base64(self, text: str): """Base64 decode args: text -> text to decode returns: the text decoded as base64 """ logger.trace("Attempting base64") + return self._dispatch(base64.b64decode, text, "base64") - return self._dispatch(base64.b64decode, text) ===========changed ref 4=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def base85(self, text: str): """Base85 decode args: text -> text to decode returns: the text decoded as base85 """ logger.trace("Attempting base85") result = None + return self._dispatch(base64.b85decode, text, "base85") - return self._dispatch(base64.b85decode, text) ===========changed ref 5=========== # module: ciphey.Decryptor.Encoding.bases class Bases: + def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): - def _dispatch(self, decoder: Callable[[str], bytes], text: str): logger.trace("Attempting base64") result = None try: result = decoder(text) # yeet turning b strings into normal stringy bois result = result.decode("utf-8") except UnicodeDecodeError as e: logger.trace("Bad unicode") result = None except binascii.Error as e: logger.trace("binascii error") result = None except ValueError: logger.trace("Failed to decode base") result = None if result is not None and self.lc.checkLanguage(result): logger.debug(f"Bases successful, returning {result}") + return self.goodRet(result, cipher=cipher) - return self.goodRet(result, cipher="Bases") else: return self.badRet() ===========changed ref 6=========== # module: ciphey.__main__ warnings.filterwarnings("ignore") # Depending on whether Ciphey is called, or Ciphey/__main__ # we need different imports to deal with both cases try: from ciphey.LanguageChecker import LanguageChecker as lc from ciphey.neuralNetworkMod.nn import NeuralNetwork from ciphey.Decryptor.basicEncryption.basic_parent import BasicParent from ciphey.Decryptor.Hash.hashParent import HashParent from ciphey.Decryptor.Encoding.encodingParent import EncodingParent + import ciphey.mathsHelper as mh except ModuleNotFoundError: from LanguageChecker import LanguageChecker as lc from neuralNetworkMod.nn import NeuralNetwork from Decryptor.basicEncryption.basic_parent import BasicParent from Decryptor.Hash.hashParent import HashParent from Decryptor.Encoding.encodingParent import EncodingParent - - - try: import mathsHelper as mh - except ModuleNotFoundError: - import ciphey.mathsHelper as mh ===========changed ref 7=========== # module: ciphey.Decryptor.Encoding.encodingParent class EncodingParent: def decrypt(self, text): self.text = text torun = [self.base64, self.binary, self.hex, self.ascii, self.morse] logger.debug(f"Encoding parent is running {torun}") """ ok so I have an array of functions and I want to apply each function to some text (text, function) but the way it works is you apply text to every item in the array (function) """ + # from multiprocessing.dummy import Pool as ThreadPool - from multiprocessing.dummy import Pool as ThreadPool + # pool = ThreadPool(4) - pool = ThreadPool(4) + # answers = pool.map(self.callDecrypt, torun) # It's not worth the thread overhead + answers = map(self.callDecrypt, torun) - answers = pool.map(self.callDecrypt, torun) for answer in answers: logger.debug(f"All answers are {answers}") # adds the LC objects together # self.lc = self.lc + answer["lc"] if answer is not None and answer["IsPlaintext?"]: logger.debug(f"Plaintext found {answer}") return answer return { "lc": self.lc, "IsPlaintext?": False, "Plaintext": None, "Cipher": None, "Extra Information": None, }
ciphey.Decryptor.Encoding.morsecode/MorseCode.unmorse_it
Modified
Ciphey~Ciphey
76aa894b37803d7262eb3c9c59036cc021c4896e
Merge branch 'master' into fixMorse
<4>:<add> m = self.MORSE_CODE_DICT_INV[char] <del> returnMsg += self.MORSE_CODE_DICT_INV[char] <5>:<add> if m == None: <add> m = "" <add> returnMsg += m <add> # after every word add a space
# module: ciphey.Decryptor.Encoding.morsecode class MorseCode: def unmorse_it(self, text): <0> returnMsg = "" <1> for word in text.split("/"): <2> for char in word.strip().split(): <3> # translates every letter <4> returnMsg += self.MORSE_CODE_DICT_INV[char] <5> # after every word add a space <6> returnMsg += " " <7> return returnMsg.strip().capitalize() <8>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.morsecode.MorseCode.__init__ self.MORSE_CODE_DICT_INV = {v: k for k, v in self.MORSE_CODE_DICT.items()}
ciphey.__main__/Ciphey.decrypt
Modified
Ciphey~Ciphey
76aa894b37803d7262eb3c9c59036cc021c4896e
Merge branch 'master' into fixMorse
<0>:<add> """Performs the decryption of text <del> """Performs the decryption of text <1>:<del> <2>:<del> Creates the probability table, calls one_level_of_decryption <3>:<del> <4>:<del> Args: <5>:<del> None, it uses class variables. <6>:<del> <7>:<del> Returns: <8>:<del> None <9>:<del> """ <10>:<del> # Read the documentation for more on this function. <11>:<del> # checks to see if inputted text is plaintext <12>:<del> result = self.lc.checkLanguage(self.text) <13>:<del> if result: <14>:<del> print("You inputted plain text!") <15>:<del> print(f"Returning {self.text}") <16>:<del> return { <17>:<del> "lc": self.lc, <18>:<del> "IsPlaintext?": True, <19>:<del> "Plaintext": self.text, <20>:<del> "Cipher": None, <21>:<del> "Extra Information": None, <22>:<del> } <23>:<del> self.probability_distribution: dict = self.ai.predictnn(self.text)[0] <24>:<del> self.what_to_choose: dict = { <25>:<del> self.hash: { <26>:<del> "sha1": self.probability_distribution[0], <27>:<del> "md5": self.probability_distribution[1], <28>:<del> "sha256": self.probability_distribution[2], <29>:<del> "sha512": self.probability_distribution[3], <30>:<del> }, <31>:<del> self.basic: {"caesar": self.probability_distribution[4]}, <32>:<del> "plaintext": {"plaintext": self.probability_distribution[5]}, <33>:<del> self.encoding: { <34>:<del> "reverse": self.probability_distribution[6], <35>:<del> "base64": self.probability_distribution[7], <36>:<del> "binary": self.probability_distribution[8], <37>:<del> "hexadecimal": self.probability_distribution[9], <38>:<del> "ascii": self.probability_distribution[10], <39>:<del> "morse": self.probability_distribution[
# module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: <0> """Performs the decryption of text <1> <2> Creates the probability table, calls one_level_of_decryption <3> <4> Args: <5> None, it uses class variables. <6> <7> Returns: <8> None <9> """ <10> # Read the documentation for more on this function. <11> # checks to see if inputted text is plaintext <12> result = self.lc.checkLanguage(self.text) <13> if result: <14> print("You inputted plain text!") <15> print(f"Returning {self.text}") <16> return { <17> "lc": self.lc, <18> "IsPlaintext?": True, <19> "Plaintext": self.text, <20> "Cipher": None, <21> "Extra Information": None, <22> } <23> self.probability_distribution: dict = self.ai.predictnn(self.text)[0] <24> self.what_to_choose: dict = { <25> self.hash: { <26> "sha1": self.probability_distribution[0], <27> "md5": self.probability_distribution[1], <28> "sha256": self.probability_distribution[2], <29> "sha512": self.probability_distribution[3], <30> }, <31> self.basic: {"caesar": self.probability_distribution[4]}, <32> "plaintext": {"plaintext": self.probability_distribution[5]}, <33> self.encoding: { <34> "reverse": self.probability_distribution[6], <35> "base64": self.probability_distribution[7], <36> "binary": self.probability_distribution[8], <37> "hexadecimal": self.probability_distribution[9], <38> "ascii": self.probability_distribution[10], <39> "morse": self.probability_distribution[</s>
===========below chunk 0=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 1 }, } logger.trace( f"The probability table before 0.1 in __main__ is {self.what_to_choose}" ) # sorts each individual sub-dictionary for key, value in self.what_to_choose.items(): for k, v in value.items(): # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. if v < 0.01: self.what_to_choose[key][k] = 0.01 logger.trace( f"The probability table after 0.1 in __main__ is {self.what_to_choose}" ) self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) # Creates and prints the probability table if not self.greppable: self.produceprobtable(self.what_to_choose) logger.debug( f"The new probability table after sorting in __main__ is {self.what_to_choose}" ) """ #for each dictionary in the dictionary # sort that dictionary #sort the overall dictionary by the first value of the new dictionary """ output = None if self.level <= 1: output = self.one_level_of_decryption() else: # TODO: make tmpfile f = open("decryptionContents.txt", "w") output = self.one_level_of_decryption(file=f) for i in range(0, self.level): # open file and go through each text item pass logger.debug(f"decrypt is outputting {output}") return</s> ===========below chunk 1=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 2 <s> go through each text item pass logger.debug(f"decrypt is outputting {output}") return output ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey config = dict() params = dict() produceprobtable(prob_table) -> None produceprobtable(self, prob_table) -> None one_level_of_decryption() -> Optional[dict] one_level_of_decryption(self) -> Optional[dict] at: ciphey.__main__.Ciphey.__init__ self.ai = NeuralNetwork() self.lc = config["checker"](config) self.mh = mh.mathsHelper() self.text: str = config["ctext"] self.basic = BasicParent(self.lc) self.hash = HashParent() self.encoding = EncodingParent(self.lc) self.level: int = 1 self.greppable: bool = config["grep"] self.probability_distribution: dict = {} self.what_to_choose: dict = {} at: ciphey.mathsHelper.mathsHelper sort_prob_table(prob_table: dict) -> dict at: ciphey.neuralNetworkMod.nn.NeuralNetwork predictnn(text) at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.morsecode class MorseCode: def unmorse_it(self, text): returnMsg = "" for word in text.split("/"): for char in word.strip().split(): # translates every letter + m = self.MORSE_CODE_DICT_INV[char] - returnMsg += self.MORSE_CODE_DICT_INV[char] + if m == None: + m = "" + returnMsg += m + # after every word add a space # after every word add a space returnMsg += " " return returnMsg.strip().capitalize()
ciphey.__main__/Ciphey.produceprobtable
Modified
Ciphey~Ciphey
76aa894b37803d7262eb3c9c59036cc021c4896e
Merge branch 'master' into fixMorse
<0>:<add> """Produces the probability table using Rich's API <del> """Produces the probability table using Rich's API <1>:<del> <2>:<del> Uses Rich's API to print the probability table. <3>:<del> <4>:<del> Args: <5>:<del> prob_table -> the probability table generated by the neural network <6>:<del> <7>:<del> Returns: <8>:<del> None, but prints the probability table. <9>:<del> <10>:<del> """ <11>:<del> logger.debug(f"Producing log table") <12>:<del> table = Table(show_header=True, header_style="bold magenta") <13>:<del> table.add_column("Name of Cipher") <14>:<del> table.add_column("Probability", justify="right") <15>:<del> # for every key, value in dict add a row <16>:<del> # I think key is self.caesarcipher and not "caesar cipher" <17>:<del> # i must callName() somewhere else in this code <18>:<del> sorted_dic: dict = {} <19>:<del> for k, v in prob_table.items(): <20>:<del> for key, value in v.items(): <21>:<del> # Prevents the table from showing pointless 0.01 probs as they're faked <22>:<del> if value == 0.01: <23>:<del> continue <24>:<del> # gets the string ready to print <25>:<del> logger.debug(f"Key is {str(key)} and value is {str(value)}") <26>:<del> val: int = round(self.mh.percentage(value, 1), 2) <27>:<del> key_str: str = str(key).capitalize() <28>:<del> # converts "Bases" to "Base" <29>:<del> if "Base" in key_str: <30>:<del> key_str = key_str[0:-2] <31>:<del> sorted_dic[key_str] = val <32>:<del> logger.debug(f"The value as percentage is {val} and key is {key_str}") <33>:<del> sorted_dic: dict = { <34>:<del> k: v <35>:<del> for k,
# module: ciphey.__main__ - - class Ciphey: - def produceprobtable(self, prob_table) -> None: <0> """Produces the probability table using Rich's API <1> <2> Uses Rich's API to print the probability table. <3> <4> Args: <5> prob_table -> the probability table generated by the neural network <6> <7> Returns: <8> None, but prints the probability table. <9> <10> """ <11> logger.debug(f"Producing log table") <12> table = Table(show_header=True, header_style="bold magenta") <13> table.add_column("Name of Cipher") <14> table.add_column("Probability", justify="right") <15> # for every key, value in dict add a row <16> # I think key is self.caesarcipher and not "caesar cipher" <17> # i must callName() somewhere else in this code <18> sorted_dic: dict = {} <19> for k, v in prob_table.items(): <20> for key, value in v.items(): <21> # Prevents the table from showing pointless 0.01 probs as they're faked <22> if value == 0.01: <23> continue <24> # gets the string ready to print <25> logger.debug(f"Key is {str(key)} and value is {str(value)}") <26> val: int = round(self.mh.percentage(value, 1), 2) <27> key_str: str = str(key).capitalize() <28> # converts "Bases" to "Base" <29> if "Base" in key_str: <30> key_str = key_str[0:-2] <31> sorted_dic[key_str] = val <32> logger.debug(f"The value as percentage is {val} and key is {key_str}") <33> sorted_dic: dict = { <34> k: v <35> for k,</s>
===========below chunk 0=========== # module: ciphey.__main__ - - class Ciphey: - def produceprobtable(self, prob_table) -> None: # offset: 1 sorted_dic.items(), key=lambda item: item[1], reverse=True ) } for k, v in sorted_dic.items(): table.add_row(k, str(v) + "%") self.console.print(table) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey.__init__ self.mh = mh.mathsHelper() self.console = Console() at: mathsHelper.mathsHelper percentage(part: float, whole: float) -> float ===========changed ref 0=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: + """Performs the decryption of text - """Performs the decryption of text - - Creates the probability table, calls one_level_of_decryption - - Args: - None, it uses class variables. - - Returns: - None - """ - # Read the documentation for more on this function. - # checks to see if inputted text is plaintext - result = self.lc.checkLanguage(self.text) - if result: - print("You inputted plain text!") - print(f"Returning {self.text}") - return { - "lc": self.lc, - "IsPlaintext?": True, - "Plaintext": self.text, - "Cipher": None, - "Extra Information": None, - } - self.probability_distribution: dict = self.ai.predictnn(self.text)[0] - self.what_to_choose: dict = { - self.hash: { - "sha1": self.probability_distribution[0], - "md5": self.probability_distribution[1], - "sha256": self.probability_distribution[2], - "sha512": self.probability_distribution[3], - }, - self.basic: {"caesar": self.probability_distribution[4]}, - "plaintext": {"plaintext": self.probability_distribution[5]}, - self.encoding: { - "reverse": self.probability_distribution[6], - "base64": self.probability_distribution[7], - "binary": self.probability_distribution[8], - "hexadecimal": self.probability_distribution[9], - "ascii": self.probability_distribution[10], - "</s> ===========changed ref 1=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 1 <s>adecimal": self.probability_distribution[9], - "ascii": self.probability_distribution[10], - "morse": self.probability_distribution[11], - }, - } - - logger.trace( - f"The probability table before 0.1 in __main__ is {self.what_to_choose}" - ) - - # sorts each individual sub-dictionary - for key, value in self.what_to_choose.items(): - for k, v in value.items(): - # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. - if v < 0.01: - self.what_to_choose[key][k] = 0.01 - logger.trace( - f"The probability table after 0.1 in __main__ is {self.what_to_choose}" - ) - - self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) - - # Creates and prints the probability table - if not self.greppable: - self.produceprobtable(self.what_to_choose) - - logger.debug( - f"The new probability table after sorting in __main__ is {self.what_to_choose}" - ) - - """ - #for each dictionary in the dictionary - # sort that dictionary - #sort the overall dictionary by the first value of the new dictionary - """ - output = None - if self.level <= 1: - output = self.</s> ===========changed ref 2=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 2 <s>level_of_decryption() - else: - # TODO: make tmpfile - f = open("decryptionContents.txt", "w") - output = self.one_level_of_decryption(file=f) - - for i in range(0, self.level): - # open file and go through each text item - pass - logger.debug(f"decrypt is outputting {output}") - return output ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.morsecode class MorseCode: def unmorse_it(self, text): returnMsg = "" for word in text.split("/"): for char in word.strip().split(): # translates every letter + m = self.MORSE_CODE_DICT_INV[char] - returnMsg += self.MORSE_CODE_DICT_INV[char] + if m == None: + m = "" + returnMsg += m + # after every word add a space # after every word add a space returnMsg += " " return returnMsg.strip().capitalize()
ciphey.__main__/Ciphey.one_level_of_decryption
Modified
Ciphey~Ciphey
76aa894b37803d7262eb3c9c59036cc021c4896e
Merge branch 'master' into fixMorse
<0>:<add> """Performs one level of encryption. <del> """Performs one level of encryption. <1>:<del> <2>:<del> Either uses alive_bar or not depending on if self.greppable is set. <3>:<del> <4>:<del> Returns: <5>:<del> None. <6>:<del> <7>:<del> """ <8>:<del> # Calls one level of decryption <9>:<del> # mainly used to control the progress bar <10>:<del> output = None <11>:<del> if self.greppable: <12>:<del> logger.debug("__main__ is running as greppable") <13>:<del> output = self.decrypt_normal() <14>:<del> else: <15>:<del> logger.debug("__main__ is running with progress bar") <16>:<del> output = self.decrypt_normal() <17>:<del> return output
# module: ciphey.__main__ - - class Ciphey: - def one_level_of_decryption(self) -> Optional[dict]: <0> """Performs one level of encryption. <1> <2> Either uses alive_bar or not depending on if self.greppable is set. <3> <4> Returns: <5> None. <6> <7> """ <8> # Calls one level of decryption <9> # mainly used to control the progress bar <10> output = None <11> if self.greppable: <12> logger.debug("__main__ is running as greppable") <13> output = self.decrypt_normal() <14> else: <15> logger.debug("__main__ is running with progress bar") <16> output = self.decrypt_normal() <17> return output <18>
===========unchanged ref 0=========== at: ciphey.__main__.Ciphey decrypt_normal(bar=None) -> Optional[dict] decrypt_normal(self, bar=None) -> Optional[dict] at: ciphey.__main__.Ciphey.__init__ self.greppable: bool = config["grep"] ===========changed ref 0=========== # module: ciphey.__main__ - - class Ciphey: - def produceprobtable(self, prob_table) -> None: + """Produces the probability table using Rich's API - """Produces the probability table using Rich's API - - Uses Rich's API to print the probability table. - - Args: - prob_table -> the probability table generated by the neural network - - Returns: - None, but prints the probability table. - - """ - logger.debug(f"Producing log table") - table = Table(show_header=True, header_style="bold magenta") - table.add_column("Name of Cipher") - table.add_column("Probability", justify="right") - # for every key, value in dict add a row - # I think key is self.caesarcipher and not "caesar cipher" - # i must callName() somewhere else in this code - sorted_dic: dict = {} - for k, v in prob_table.items(): - for key, value in v.items(): - # Prevents the table from showing pointless 0.01 probs as they're faked - if value == 0.01: - continue - # gets the string ready to print - logger.debug(f"Key is {str(key)} and value is {str(value)}") - val: int = round(self.mh.percentage(value, 1), 2) - key_str: str = str(key).capitalize() - # converts "Bases" to "Base" - if "Base" in key_str: - key_str = key_str[0:-2] - sorted_dic[key_str] = val - logger.debug(f"The value as percentage is {val} and key is {key_str}") - sorted_dic: dict = { </s> ===========changed ref 1=========== # module: ciphey.__main__ - - class Ciphey: - def produceprobtable(self, prob_table) -> None: # offset: 1 <s>"The value as percentage is {val} and key is {key_str}") - sorted_dic: dict = { - k: v - for k, v in sorted( - sorted_dic.items(), key=lambda item: item[1], reverse=True - ) - } - for k, v in sorted_dic.items(): - table.add_row(k, str(v) + "%") - - self.console.print(table) - return None ===========changed ref 2=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: + """Performs the decryption of text - """Performs the decryption of text - - Creates the probability table, calls one_level_of_decryption - - Args: - None, it uses class variables. - - Returns: - None - """ - # Read the documentation for more on this function. - # checks to see if inputted text is plaintext - result = self.lc.checkLanguage(self.text) - if result: - print("You inputted plain text!") - print(f"Returning {self.text}") - return { - "lc": self.lc, - "IsPlaintext?": True, - "Plaintext": self.text, - "Cipher": None, - "Extra Information": None, - } - self.probability_distribution: dict = self.ai.predictnn(self.text)[0] - self.what_to_choose: dict = { - self.hash: { - "sha1": self.probability_distribution[0], - "md5": self.probability_distribution[1], - "sha256": self.probability_distribution[2], - "sha512": self.probability_distribution[3], - }, - self.basic: {"caesar": self.probability_distribution[4]}, - "plaintext": {"plaintext": self.probability_distribution[5]}, - self.encoding: { - "reverse": self.probability_distribution[6], - "base64": self.probability_distribution[7], - "binary": self.probability_distribution[8], - "hexadecimal": self.probability_distribution[9], - "ascii": self.probability_distribution[10], - "</s> ===========changed ref 3=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 1 <s>adecimal": self.probability_distribution[9], - "ascii": self.probability_distribution[10], - "morse": self.probability_distribution[11], - }, - } - - logger.trace( - f"The probability table before 0.1 in __main__ is {self.what_to_choose}" - ) - - # sorts each individual sub-dictionary - for key, value in self.what_to_choose.items(): - for k, v in value.items(): - # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. - if v < 0.01: - self.what_to_choose[key][k] = 0.01 - logger.trace( - f"The probability table after 0.1 in __main__ is {self.what_to_choose}" - ) - - self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) - - # Creates and prints the probability table - if not self.greppable: - self.produceprobtable(self.what_to_choose) - - logger.debug( - f"The new probability table after sorting in __main__ is {self.what_to_choose}" - ) - - """ - #for each dictionary in the dictionary - # sort that dictionary - #sort the overall dictionary by the first value of the new dictionary - """ - output = None - if self.level <= 1: - output = self.</s> ===========changed ref 4=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 2 <s>level_of_decryption() - else: - # TODO: make tmpfile - f = open("decryptionContents.txt", "w") - output = self.one_level_of_decryption(file=f) - - for i in range(0, self.level): - # open file and go through each text item - pass - logger.debug(f"decrypt is outputting {output}") - return output
ciphey.__main__/Ciphey.decrypt_normal
Modified
Ciphey~Ciphey
76aa894b37803d7262eb3c9c59036cc021c4896e
Merge branch 'master' into fixMorse
<0>:<add> """Called by one_level_of_decryption <del> """Called by one_level_of_decryption <1>:<del> <2>:<del> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3>:<del> <4>:<del> Args: <5>:<del> bar -> whether or not to use alive_Bar <6>:<del> <7>:<del> Returns: <8>:<del> str if found, or None if not <9>:<del> <10>:<del> """ <11>:<del> # This is redundant <12>:<del> # result = self.lc.checkLanguage(self.text) <13>:<del> # if result: <14>:<del> # print("You inputted plain text!") <15>:<del> # print(f"Returning {self.text}") <16>:<del> # return self.text <17>:<del> <18>:<del> logger.debug(f"In decrypt_normal") <19>:<del> for key, val in self.what_to_choose.items(): <20>:<del> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <21>:<del> if not isinstance(key, str): <22>:<del> key.setProbTable(val) <23>:<del> ret: dict = key.decrypt(self.text) <24>:<del> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <25>:<del> logger.debug( <26>:<del> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <27>:<del> ) <28>:<del> <29>:<del> if ret["IsPlaintext?"]: <30>:<del> logger.debug(f"Ret is plaintext") <31>:<del> print(ret["Plaintext"]) <32>:<del> if self.cipher_info: <33>:<del> if ret["Extra Information"] is not None: <34>:<del> print( <35>:<del> "The cipher used is", <36>:<del> ret["Cipher"] + ".", <37>:<del> ret["Extra Information"] + ".", <38>:<del> ) <39>:<del> else: <40>:<del> print("The
# module: ciphey.__main__ - - class Ciphey: - def decrypt_normal(self, bar=None) -> Optional[dict]: <0> """Called by one_level_of_decryption <1> <2> Performs a decryption, but mainly parses the internal data packet and prints useful information. <3> <4> Args: <5> bar -> whether or not to use alive_Bar <6> <7> Returns: <8> str if found, or None if not <9> <10> """ <11> # This is redundant <12> # result = self.lc.checkLanguage(self.text) <13> # if result: <14> # print("You inputted plain text!") <15> # print(f"Returning {self.text}") <16> # return self.text <17> <18> logger.debug(f"In decrypt_normal") <19> for key, val in self.what_to_choose.items(): <20> # https://stackoverflow.com/questions/4843173/how-to-check-if-type-of-a-variable-is-string <21> if not isinstance(key, str): <22> key.setProbTable(val) <23> ret: dict = key.decrypt(self.text) <24> logger.debug(f"Decrypt normal in __main__ ret is {ret}") <25> logger.debug( <26> f"The plaintext is {ret['Plaintext']} and the extra information is {ret['Cipher']} and {ret['Extra Information']}" <27> ) <28> <29> if ret["IsPlaintext?"]: <30> logger.debug(f"Ret is plaintext") <31> print(ret["Plaintext"]) <32> if self.cipher_info: <33> if ret["Extra Information"] is not None: <34> print( <35> "The cipher used is", <36> ret["Cipher"] + ".", <37> ret["Extra Information"] + ".", <38> ) <39> else: <40> print("The</s>
===========below chunk 0=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt_normal(self, bar=None) -> Optional[dict]: # offset: 1 return ret logger.debug("No encryption found") print( """No encryption found. Here are some tips to help crack the cipher: * Use the probability table to work out what it could be. Base = base16, base32, base64 etc. * If the probability table says 'Caesar Cipher' then it is a normal encryption that \ Ciphey cannot decrypt yet. * If Ciphey think's it's a hash, try using hash-identifier to find out what hash it is, \ and then HashCat to crack the hash. * The encryption may not contain normal English plaintext. It could be coordinates or \ another object no found in the dictionary. Use 'ciphey -d true > log.txt' to generate a log \ file of all attempted decryptions and manually search it.""" ) return None ===========unchanged ref 0=========== at: ciphey.__main__.Ciphey.__init__ self.text: str = config["ctext"] self.cipher_info = config["info"] self.what_to_choose: dict = {} at: ciphey.__main__.Ciphey.decrypt self.what_to_choose: dict = { self.hash: { "sha1": self.probability_distribution[0], "md5": self.probability_distribution[1], "sha256": self.probability_distribution[2], "sha512": self.probability_distribution[3], }, self.basic: {"caesar": self.probability_distribution[4]}, "plaintext": {"plaintext": self.probability_distribution[5]}, self.encoding: { "reverse": self.probability_distribution[6], "base64": self.probability_distribution[7], "binary": self.probability_distribution[8], "hexadecimal": self.probability_distribution[9], "ascii": self.probability_distribution[10], "morse": self.probability_distribution[11], }, } self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) ===========changed ref 0=========== # module: ciphey.__main__ - - class Ciphey: - def one_level_of_decryption(self) -> Optional[dict]: + """Performs one level of encryption. - """Performs one level of encryption. - - Either uses alive_bar or not depending on if self.greppable is set. - - Returns: - None. - - """ - # Calls one level of decryption - # mainly used to control the progress bar - output = None - if self.greppable: - logger.debug("__main__ is running as greppable") - output = self.decrypt_normal() - else: - logger.debug("__main__ is running with progress bar") - output = self.decrypt_normal() - return output ===========changed ref 1=========== # module: ciphey.__main__ - - class Ciphey: - def produceprobtable(self, prob_table) -> None: + """Produces the probability table using Rich's API - """Produces the probability table using Rich's API - - Uses Rich's API to print the probability table. - - Args: - prob_table -> the probability table generated by the neural network - - Returns: - None, but prints the probability table. - - """ - logger.debug(f"Producing log table") - table = Table(show_header=True, header_style="bold magenta") - table.add_column("Name of Cipher") - table.add_column("Probability", justify="right") - # for every key, value in dict add a row - # I think key is self.caesarcipher and not "caesar cipher" - # i must callName() somewhere else in this code - sorted_dic: dict = {} - for k, v in prob_table.items(): - for key, value in v.items(): - # Prevents the table from showing pointless 0.01 probs as they're faked - if value == 0.01: - continue - # gets the string ready to print - logger.debug(f"Key is {str(key)} and value is {str(value)}") - val: int = round(self.mh.percentage(value, 1), 2) - key_str: str = str(key).capitalize() - # converts "Bases" to "Base" - if "Base" in key_str: - key_str = key_str[0:-2] - sorted_dic[key_str] = val - logger.debug(f"The value as percentage is {val} and key is {key_str}") - sorted_dic: dict = { </s> ===========changed ref 2=========== # module: ciphey.__main__ - - class Ciphey: - def produceprobtable(self, prob_table) -> None: # offset: 1 <s>"The value as percentage is {val} and key is {key_str}") - sorted_dic: dict = { - k: v - for k, v in sorted( - sorted_dic.items(), key=lambda item: item[1], reverse=True - ) - } - for k, v in sorted_dic.items(): - table.add_row(k, str(v) + "%") - - self.console.print(table) - return None
ciphey.__main__/arg_parsing
Modified
Ciphey~Ciphey
76aa894b37803d7262eb3c9c59036cc021c4896e
Merge branch 'master' into fixMorse
<0>:<add> """This function parses arguments. <del> """This function parses arguments. <1>:<del> <2>:<del> Args: <3>:<del> None <4>:<del> Returns: <5>:<del> The config to be passed around for the rest of time <6>:<del> """ <7>:<del> parser = argparse.ArgumentParser( <8>:<del> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n <9>:<del> Examples: <10>:<del> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true <11>:<del> """ <12>:<del> ) <13>:<del> parser.add_argument( <14>:<del> "-g", <15>:<del> "--greppable", <16>:<del> help="Only output the answer, no progress bars or information. Useful for grep", <17>:<del> action="store_true", <18>:<del> required=False, <19>:<del> default=False <20>:<del> ) <21>:<del> parser.add_argument("-t", "--text", help="Text to decrypt", required=False) <22>:<del> parser.add_argument( <23>:<del> "-i", <24>:<del> "--info", <25>:<del> help="Do you want information on the cipher used?", <26>:<del> action="store_true", <27>:<del> required=False, <28>:<del> default=False <29>:<del> ) <30>:<del> parser.add_argument( <31>:<del> "-d", <32>:<del> "--debug", <33>:<del> help="Activates debug mode", # Actually "INFO" level is used, but ¯\_(ツ)_/¯ <34>:<del> required=False, <35>:<del> action="store_true", <36>:<del> ) <37>:<del> parser.add_argument( <38>:<del> "-D", <39>:<del> "--trace", <40>:<del> help="More verbose than debug mode. Shadows --debug", <41>:<del> required=False, <42>:<del> action="store_true", <43>:<del> ) <44>:<del> parser.add_argument( <45>:<del> "-q", <46>:<del> "--quiet", <47>:<del> help="
# module: ciphey.__main__ - - def arg_parsing() -> Optional[dict]: <0> """This function parses arguments. <1> <2> Args: <3> None <4> Returns: <5> The config to be passed around for the rest of time <6> """ <7> parser = argparse.ArgumentParser( <8> description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n <9> Examples: <10> python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true <11> """ <12> ) <13> parser.add_argument( <14> "-g", <15> "--greppable", <16> help="Only output the answer, no progress bars or information. Useful for grep", <17> action="store_true", <18> required=False, <19> default=False <20> ) <21> parser.add_argument("-t", "--text", help="Text to decrypt", required=False) <22> parser.add_argument( <23> "-i", <24> "--info", <25> help="Do you want information on the cipher used?", <26> action="store_true", <27> required=False, <28> default=False <29> ) <30> parser.add_argument( <31> "-d", <32> "--debug", <33> help="Activates debug mode", # Actually "INFO" level is used, but ¯\_(ツ)_/¯ <34> required=False, <35> action="store_true", <36> ) <37> parser.add_argument( <38> "-D", <39> "--trace", <40> help="More verbose than debug mode. Shadows --debug", <41> required=False, <42> action="store_true", <43> ) <44> parser.add_argument( <45> "-q", <46> "--quiet", <47> help="</s>
===========below chunk 0=========== # module: ciphey.__main__ - - def arg_parsing() -> Optional[dict]: # offset: 1 required=False, action="store_true", ) parser.add_argument( "-a", "--checker", help="Uses the given internal language checker. Defaults to brandon", required=False, ) parser.add_argument( "-A", "--checker-file", help="Uses the language checker at the given path", required=False, ) parser.add_argument( "-w", "--wordlist", help="Uses the given internal wordlist", required=False, ) parser.add_argument( "-W", "--wordlist-file", help="Uses the wordlist at the given path", required=False, ) parser.add_argument( "-p", "--param", help="Passes a parameter to the language checker", action="append", required=False, default=[] ) parser.add_argument( "-l", "--list-params", help="Lists the parameters of the selected module", action="store_true", required=False, ) parser.add_argument("rest", nargs=argparse.REMAINDER) args = vars(parser.parse_args()) # the below text does: # if -t is supplied, use that # if ciphey is called like: # ciphey 'encrypted text' use that # else if data is piped like: # echo 'hello' | ciphey use that # if no data is supplied, no arguments supplied. text = None if args["text"] is not None: text = args["text"] elif len</s> ===========below chunk 1=========== # module: ciphey.__main__ - - def arg_parsing() -> Optional[dict]: # offset: 2 <s> text = None if args["text"] is not None: text = args["text"] elif len(sys.argv) > 1: text = args["rest"][0] elif not sys.stdin.isatty(): text = str(sys.stdin.read()) else: print("No text input given!") return None if len(sys.argv) == 1: print("No arguments were supplied. Look at the help menu with -h or --help") return None args["text"] = text if not args["rest"]: args.pop("rest") if len(args["text"]) < 3: print("A string of less than 3 chars cannot be interpreted by Ciphey.") return None config = dict() # Now we can walk through the arguments, expanding them into a canonical form # # First, we go over simple args config["ctext"] = args["text"] config["grep"] = args["greppable"] config["info"] = args["info"] # Try to work out how verbose we should be if args["trace"]: config["debug"] = "TRACE" elif args["debug"]: config["debug"] = "DEBUG" elif args["quiet"]: config["debug"] = "ERROR" else: config["debug"] = "WARNING" # Try to locate language checker module # TODO: actually implement this from ciphey.LanguageChecker.brandon import ciphey_language_checker as brandon config["checker"] = brandon # Try to locate language checker module </s> ===========below chunk 2=========== # module: ciphey.__main__ - - def arg_parsing() -> Optional[dict]: # offset: 3 <s> # TODO: actually implement this (should be similar) import cipheydists config["wordlist"] = set(cipheydists.get_list("english")) # Now we fill in the params *shudder* config["params"] = {} for i in args["param"]: key, value = i.split('=', 1) config["params"][key] = value return config ===========unchanged ref 0=========== at: argparse REMAINDER = '...' ArgumentParser(prog: Optional[str]=..., usage: Optional[str]=..., description: Optional[str]=..., epilog: Optional[str]=..., parents: Sequence[ArgumentParser]=..., formatter_class: _FormatterClass=..., prefix_chars: str=..., fromfile_prefix_chars: Optional[str]=..., argument_default: Any=..., conflict_handler: str=..., add_help: bool=..., allow_abbrev: bool=...) at: argparse.ArgumentParser parse_args(args: Optional[Sequence[Text]], namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]]=...) -> Namespace parse_args(*, namespace: None) -> Namespace parse_args(args: Optional[Sequence[Text]], namespace: _N) -> _N parse_args(*, namespace: _N) -> _N at: argparse._ActionsContainer add_argument(*name_or_flags: Text, action: Union[Text, Type[Action]]=..., nargs: Union[int, Text]=..., const: Any=..., default: Any=..., type: Union[Callable[[Text], _T], Callable[[str], _T], FileType]=..., choices: Iterable[_T]=..., required: bool=..., help: Optional[Text]=..., metavar: Optional[Union[Text, Tuple[Text, ...]]]=..., dest: Optional[Text]=..., version: Text=..., **kwargs: Any) -> Action at: ciphey.LanguageChecker.brandon ciphey_language_checker = Brandon at: sys argv: List[str] stdin: TextIO at: typing.IO __slots__ = () isatty() -> bool read(n: int=...) -> AnyStr at: typing.MutableMapping pop(key: _KT, default: Union[_VT, _T]=...) -> Union[_VT, _T] pop(key: _KT) -> _VT ===========changed ref 0=========== # module: ciphey.__main__ - - class Ciphey: - def one_level_of_decryption(self) -> Optional[dict]: + """Performs one level of encryption. - """Performs one level of encryption. - - Either uses alive_bar or not depending on if self.greppable is set. - - Returns: - None. - - """ - # Calls one level of decryption - # mainly used to control the progress bar - output = None - if self.greppable: - logger.debug("__main__ is running as greppable") - output = self.decrypt_normal() - else: - logger.debug("__main__ is running with progress bar") - output = self.decrypt_normal() - return output
ciphey.__main__/main
Modified
Ciphey~Ciphey
76aa894b37803d7262eb3c9c59036cc021c4896e
Merge branch 'master' into fixMorse
<0>:<add> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <del> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <1>:<del> <2>:<del> It gets the arguments in the function definition using locals() <3>:<del> if withArgs is True, that means this is being called with command line args <4>:<del> so go to arg_parsing() to get those args <5>:<del> we then update locals() with the new command line args and remove "withArgs" <6>:<del> This function then calls call_encryption(**result) which passes our dict of args <7>:<del> to the function as its own arguments using dict unpacking. <8>:<del> <9>:<del> Returns: <10>:<del> The output of the decryption. <11>:<del> """ <12>:<del> # We must fill in the arguments if they are not provided <13>:<del> if config is None: <14>:<del> config = arg_parsing() <15>:<del> # Check if we errored out <16>:<del> if config is None: <17>:<del> return None <18>:<del> <19>:<del> # Now we have working arguments, we can expand it and pass it to the Ciphey constructor <20>:<del> cipher_obj = Ciphey(config) <21>:<del> return cipher_obj.decrypt()
# module: ciphey.__main__ - - def main(config: Dict[str, object] = None) -> Optional[dict]: <0> """Function to deal with arguments. Either calls with args or not. Makes Pytest work. <1> <2> It gets the arguments in the function definition using locals() <3> if withArgs is True, that means this is being called with command line args <4> so go to arg_parsing() to get those args <5> we then update locals() with the new command line args and remove "withArgs" <6> This function then calls call_encryption(**result) which passes our dict of args <7> to the function as its own arguments using dict unpacking. <8> <9> Returns: <10> The output of the decryption. <11> """ <12> # We must fill in the arguments if they are not provided <13> if config is None: <14> config = arg_parsing() <15> # Check if we errored out <16> if config is None: <17> return None <18> <19> # Now we have working arguments, we can expand it and pass it to the Ciphey constructor <20> cipher_obj = Ciphey(config) <21> return cipher_obj.decrypt() <22>
===========unchanged ref 0=========== at: ciphey.__main__ Ciphey(config) arg_parsing() -> Optional[dict] at: ciphey.__main__.Ciphey decrypt() -> Optional[Dict] decrypt(self) -> Optional[Dict] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: + """Performs the decryption of text - """Performs the decryption of text - - Creates the probability table, calls one_level_of_decryption - - Args: - None, it uses class variables. - - Returns: - None - """ - # Read the documentation for more on this function. - # checks to see if inputted text is plaintext - result = self.lc.checkLanguage(self.text) - if result: - print("You inputted plain text!") - print(f"Returning {self.text}") - return { - "lc": self.lc, - "IsPlaintext?": True, - "Plaintext": self.text, - "Cipher": None, - "Extra Information": None, - } - self.probability_distribution: dict = self.ai.predictnn(self.text)[0] - self.what_to_choose: dict = { - self.hash: { - "sha1": self.probability_distribution[0], - "md5": self.probability_distribution[1], - "sha256": self.probability_distribution[2], - "sha512": self.probability_distribution[3], - }, - self.basic: {"caesar": self.probability_distribution[4]}, - "plaintext": {"plaintext": self.probability_distribution[5]}, - self.encoding: { - "reverse": self.probability_distribution[6], - "base64": self.probability_distribution[7], - "binary": self.probability_distribution[8], - "hexadecimal": self.probability_distribution[9], - "ascii": self.probability_distribution[10], - "</s> ===========changed ref 1=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 1 <s>adecimal": self.probability_distribution[9], - "ascii": self.probability_distribution[10], - "morse": self.probability_distribution[11], - }, - } - - logger.trace( - f"The probability table before 0.1 in __main__ is {self.what_to_choose}" - ) - - # sorts each individual sub-dictionary - for key, value in self.what_to_choose.items(): - for k, v in value.items(): - # Sets all 0 probabilities to 0.01, we want Ciphey to try all decryptions. - if v < 0.01: - self.what_to_choose[key][k] = 0.01 - logger.trace( - f"The probability table after 0.1 in __main__ is {self.what_to_choose}" - ) - - self.what_to_choose: dict = self.mh.sort_prob_table(self.what_to_choose) - - # Creates and prints the probability table - if not self.greppable: - self.produceprobtable(self.what_to_choose) - - logger.debug( - f"The new probability table after sorting in __main__ is {self.what_to_choose}" - ) - - """ - #for each dictionary in the dictionary - # sort that dictionary - #sort the overall dictionary by the first value of the new dictionary - """ - output = None - if self.level <= 1: - output = self.</s> ===========changed ref 2=========== # module: ciphey.__main__ - - class Ciphey: - def decrypt(self) -> Optional[Dict]: # offset: 2 <s>level_of_decryption() - else: - # TODO: make tmpfile - f = open("decryptionContents.txt", "w") - output = self.one_level_of_decryption(file=f) - - for i in range(0, self.level): - # open file and go through each text item - pass - logger.debug(f"decrypt is outputting {output}") - return output ===========changed ref 3=========== # module: ciphey.__main__ - - def arg_parsing() -> Optional[dict]: + """This function parses arguments. - """This function parses arguments. - - Args: - None - Returns: - The config to be passed around for the rest of time - """ - parser = argparse.ArgumentParser( - description="""Automated decryption tool. Put in the encrypted text and Ciphey will decrypt it.\n - Examples: - python3 ciphey -t "aGVsbG8gbXkgYmFieQ==" -d true -c true - """ - ) - parser.add_argument( - "-g", - "--greppable", - help="Only output the answer, no progress bars or information. Useful for grep", - action="store_true", - required=False, - default=False - ) - parser.add_argument("-t", "--text", help="Text to decrypt", required=False) - parser.add_argument( - "-i", - "--info", - help="Do you want information on the cipher used?", - action="store_true", - required=False, - default=False - ) - parser.add_argument( - "-d", - "--debug", - help="Activates debug mode", # Actually "INFO" level is used, but ¯\_(ツ)_/¯ - required=False, - action="store_true", - ) - parser.add_argument( - "-D", - "--trace", - help="More verbose than debug mode. Shadows --debug", - required=False, - action="store_true", - ) - parser.add_argument( - "-q", - </s>
ciphey.Decryptor.Encoding.morsecode/MorseCode.checkIfMorse
Modified
Ciphey~Ciphey
6a16998ef0014cd0e983cee7d8e5a0c0fd64fc25
I fixed Morse Code
<0>:<add> # return set(self.ALLOWED).issuperset(text) <del> return set(self.ALLOWED).issuperset(text) <1>:<add> return "-" or "." in text
# module: ciphey.Decryptor.Encoding.morsecode + class MorseCode: def checkIfMorse(self, text): <0> return set(self.ALLOWED).issuperset(text) <1>
ciphey.Decryptor.Encoding.morsecode/MorseCode.unmorse_it
Modified
Ciphey~Ciphey
6a16998ef0014cd0e983cee7d8e5a0c0fd64fc25
I fixed Morse Code
<4>:<add> try: <add> m = self.MORSE_CODE_DICT_INV[char] <del> m = self.MORSE_CODE_DICT_INV[char] <5>:<add> except KeyError: <del> if m == None: <7>:<add> returnMsg = returnMsg + m <del> returnMsg += m <10>:<add> returnMsg = returnMsg + " " <del> returnMsg += " " <11>:<add> print(returnMsg)
# module: ciphey.Decryptor.Encoding.morsecode + class MorseCode: def unmorse_it(self, text): <0> returnMsg = "" <1> for word in text.split("/"): <2> for char in word.strip().split(): <3> # translates every letter <4> m = self.MORSE_CODE_DICT_INV[char] <5> if m == None: <6> m = "" <7> returnMsg += m <8> # after every word add a space <9> # after every word add a space <10> returnMsg += " " <11> return returnMsg.strip().capitalize() <12>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.morsecode.MorseCode.__init__ self.MORSE_CODE_DICT_INV = {v: k for k, v in self.MORSE_CODE_DICT.items()} ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.morsecode + class MorseCode: def checkIfMorse(self, text): + # return set(self.ALLOWED).issuperset(text) - return set(self.ALLOWED).issuperset(text) + return "-" or "." in text
tests.test_encoding/TestEncoding.test_morse
Modified
Ciphey~Ciphey
6a16998ef0014cd0e983cee7d8e5a0c0fd64fc25
I fixed Morse Code
<2>:<add> logger.remove() <add> logger.configure() <add> logger.add(sink=sys.stderr, level="TRACE", colorize=True) <add> logger.opt(colors=True) <add> logger.error(f"""Debug level set to {config["debug"]}""") <add> a = "| .... . .-.. .-.. ---/../.- --/.-/-.-. .... .. .-.. -../..-. .-. --- --/--- ..- -/... .--. .- -.-. ./.- -. -../../.-.. .. -.- ./-.-. -.-- -... . .-./.- -. -../-.-. .- -" <del> a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." <4>:<add> logger.debug(result) <add> logger.debug(result)
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_morse(self): <0> lc = Brandon(config) <1> ep = EncodingParent(lc) <2> a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." <3> result = ep.decrypt(a) <4> self.assertEqual(result["IsPlaintext?"], True) <5>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent decrypt(text) at: ciphey.LanguageChecker.brandon Brandon(config: dict) at: tests.test_encoding config = make_default_config("") ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.morsecode + class MorseCode: def checkIfMorse(self, text): + # return set(self.ALLOWED).issuperset(text) - return set(self.ALLOWED).issuperset(text) + return "-" or "." in text ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.morsecode + + + x = MorseCode(lc=None) + x.unmorse_it( + "| .... . .-.. .-.. ---/../.- --/.-/-.-. .... .. .-.. -../..-. .-. --- --/--- ..- -/... .--. .- -.-. ./.- -. -../../.-.. .. -.- ./-.-. -.-- -... . .-./.- -. -../-.-. .- -" + ) - ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.morsecode + class MorseCode: def unmorse_it(self, text): returnMsg = "" for word in text.split("/"): for char in word.strip().split(): # translates every letter + try: + m = self.MORSE_CODE_DICT_INV[char] - m = self.MORSE_CODE_DICT_INV[char] + except KeyError: - if m == None: m = "" + returnMsg = returnMsg + m - returnMsg += m # after every word add a space # after every word add a space + returnMsg = returnMsg + " " - returnMsg += " " + print(returnMsg) return returnMsg.strip().capitalize()
tests.test_encoding/TestEncoding.test_base32
Modified
Ciphey~Ciphey
6a16998ef0014cd0e983cee7d8e5a0c0fd64fc25
I fixed Morse Code
<0>:<del> logger.remove() <1>:<add> # logger.configure() <del> logger.configure() <2>:<add> # logger.add(sink=sys.stderr, level="TRACE", colorize=True) <del> logger.add(sink=sys.stderr, level="TRACE", colorize=True) <3>:<add> # logger.opt(colors=True) <del> logger.opt(colors=True) <4>:<add> # logger.error(f"""Debug level set to {config["debug"]}""") <del> logger.error(f"""Debug level set to {config["debug"]}""")
# module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_base32(self): <0> logger.remove() <1> logger.configure() <2> logger.add(sink=sys.stderr, level="TRACE", colorize=True) <3> logger.opt(colors=True) <4> logger.error(f"""Debug level set to {config["debug"]}""") <5> <6> lc = Brandon(config) <7> ep = EncodingParent(lc) <8> a = "NBSWY3DPEBWXSIDOMFWWKIDJOMQGEZLF" <9> result = ep.decrypt(a) <10> self.assertEqual(result["IsPlaintext?"], True) <11>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.encodingParent EncodingParent(lc) at: ciphey.Decryptor.Encoding.encodingParent.EncodingParent decrypt(text) at: ciphey.LanguageChecker.brandon Brandon(config: dict) at: sys stderr: TextIO at: tests.test_encoding config = make_default_config("") ===========changed ref 0=========== # module: tests.test_encoding class TestEncoding(unittest.TestCase): def test_morse(self): lc = Brandon(config) ep = EncodingParent(lc) + logger.remove() + logger.configure() + logger.add(sink=sys.stderr, level="TRACE", colorize=True) + logger.opt(colors=True) + logger.error(f"""Debug level set to {config["debug"]}""") + a = "| .... . .-.. .-.. ---/../.- --/.-/-.-. .... .. .-.. -../..-. .-. --- --/--- ..- -/... .--. .- -.-. ./.- -. -../../.-.. .. -.- ./-.-. -.-- -... . .-./.- -. -../-.-. .- -" - a = ".... . .-.. .-.. --- / -- -.-- / -. .- -- . / .. ... / -... .-. .- -. -.. --- -." result = ep.decrypt(a) + logger.debug(result) + logger.debug(result) self.assertEqual(result["IsPlaintext?"], True) ===========changed ref 1=========== # module: ciphey.Decryptor.Encoding.morsecode + class MorseCode: def checkIfMorse(self, text): + # return set(self.ALLOWED).issuperset(text) - return set(self.ALLOWED).issuperset(text) + return "-" or "." in text ===========changed ref 2=========== # module: ciphey.Decryptor.Encoding.morsecode + + + x = MorseCode(lc=None) + x.unmorse_it( + "| .... . .-.. .-.. ---/../.- --/.-/-.-. .... .. .-.. -../..-. .-. --- --/--- ..- -/... .--. .- -.-. ./.- -. -../../.-.. .. -.- ./-.-. -.-- -... . .-./.- -. -../-.-. .- -" + ) - ===========changed ref 3=========== # module: ciphey.Decryptor.Encoding.morsecode + class MorseCode: def unmorse_it(self, text): returnMsg = "" for word in text.split("/"): for char in word.strip().split(): # translates every letter + try: + m = self.MORSE_CODE_DICT_INV[char] - m = self.MORSE_CODE_DICT_INV[char] + except KeyError: - if m == None: m = "" + returnMsg = returnMsg + m - returnMsg += m # after every word add a space # after every word add a space + returnMsg = returnMsg + " " - returnMsg += " " + print(returnMsg) return returnMsg.strip().capitalize()
noxfile/coverage
Modified
Ciphey~Ciphey
f71b59254c9f60a146c3bf0c77e04897a8b2a1ef
Fixing my mistakes take 2
<3>:<add> session.run("coverage", "xml", "--fail-under=0") <del> session.run("coverage", "xml", "--fail-under=0", "--patch=off")
# module: noxfile @nox.session(python="3.8") def coverage(session: Session) -> None: <0> """Upload coverage data.""" <1> install_with_constraints(session, "coverage[toml]", "codecov") <2> session.run("pip3", "install", "cipheydists") <3> session.run("coverage", "xml", "--fail-under=0", "--patch=off") <4> session.run("codecov", *session.posargs) <5>
===========unchanged ref 0=========== at: noxfile install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None
tests.generate_tests/test_generator.main
Modified
Ciphey~Ciphey
f45e8bc12cedbd24f8803622fe45a5af6f495b35
Tests should now theoretically work
<1>:<add> f.write("from ciphey.__main__ import main, make_default_config")
# module: tests.generate_tests class test_generator: def main(self): <0> with open("test_main_generated.py", "w") as f: <1> print("Opened fild") <2> for i in track(range(1, self.HOW_MANY_TESTS)): <3> print("In the for loop") <4> x = self.enCiphey_obj.getRandomEncryptedSentence() <5> print(x) <6> # if x["CipherUsed"] == "MorseCode": <7> # self.make_test_lc_true_template(cipher=x) <8> to_append = self.make_test_lc_true_template(cipher=x) <9> print(f"Adding {to_append}") <10> f.write(to_append) <11>
===========unchanged ref 0=========== at: enciphey.encipher getRandomEncryptedSentence() at: io.BufferedReader write(self, buffer: ReadableBuffer, /) -> int at: tests.generate_tests.test_generator make_test_lc_true_template(cipher) make_test_lc_true_template(self, cipher) at: tests.generate_tests.test_generator.__init__ self.HOW_MANY_TESTS = 2 self.enCiphey_obj = enciphey.encipher() at: typing.BinaryIO __slots__ = () write(s: AnyStr) -> int at: typing.IO __slots__ = () write(s: AnyStr) -> int
tests.generate_tests/test_generator.make_test_lc_true_template
Modified
Ciphey~Ciphey
f45e8bc12cedbd24f8803622fe45a5af6f495b35
Tests should now theoretically work
<4>:<add> cfg = make_default_config({cipher['Encrypted Texts']['EncryptedText']}) <del> res = ciphey.main('{cipher['Encrypted Texts']['EncryptedText']}') <5>:<add> cfg["debug"] = "TRACE" <add> result = main(cfg) <6>:<add> assert result["IsPlaintext?"] == True <del> assert lc.checkLanguage(res) == True
# module: tests.generate_tests class test_generator: def make_test_lc_true_template(self, cipher): <0> id = self.randomString(8) <1> return f""" <2> def test_{cipher['Encrypted Texts']['CipherUsed']}_{id}(): <3> # {cipher} <4> res = ciphey.main('{cipher['Encrypted Texts']['EncryptedText']}') <5> <6> assert lc.checkLanguage(res) == True <7> """ <8>
===========unchanged ref 0=========== at: tests.generate_tests.test_generator randomString(stringLength) ===========changed ref 0=========== # module: tests.generate_tests class test_generator: def main(self): with open("test_main_generated.py", "w") as f: + f.write("from ciphey.__main__ import main, make_default_config") print("Opened fild") for i in track(range(1, self.HOW_MANY_TESTS)): print("In the for loop") x = self.enCiphey_obj.getRandomEncryptedSentence() print(x) # if x["CipherUsed"] == "MorseCode": # self.make_test_lc_true_template(cipher=x) to_append = self.make_test_lc_true_template(cipher=x) print(f"Adding {to_append}") f.write(to_append)
tests.generate_tests/test_generator.make_test_true_template
Modified
Ciphey~Ciphey
8794c1a2ee49bef807250eff8d1ea4f6d69a7c0a
Update generate_tests.py
<4>:<add> res = ciphey.main('''{cipher['Encrypted Texts']['EncryptedText']}''') <del> res = ciphey.main('{cipher['Encrypted Texts']['EncryptedText']}')
# module: tests.generate_tests class test_generator: def make_test_true_template(self, cipher): <0> id = self.randomString(8) <1> return f""" <2> def test_{cipher['Encrypted Texts']['CipherUsed']}_{id}(): <3> # {cipher} <4> res = ciphey.main('{cipher['Encrypted Texts']['EncryptedText']}') <5> assert(res == {cipher['Encrypted Texts']['PlainText']}) <6> """ <7>
===========unchanged ref 0=========== at: tests.generate_tests.test_generator randomString(stringLength)
tests.generate_tests/test_generator.make_test_lc_true_template
Modified
Ciphey~Ciphey
8794c1a2ee49bef807250eff8d1ea4f6d69a7c0a
Update generate_tests.py
<4>:<add> cfg = make_default_config('''{cipher['Encrypted Texts']['EncryptedText']}''') <del> cfg = make_default_config({cipher['Encrypted Texts']['EncryptedText']})
# module: tests.generate_tests class test_generator: def make_test_lc_true_template(self, cipher): <0> id = self.randomString(8) <1> return f""" <2> def test_{cipher['Encrypted Texts']['CipherUsed']}_{id}(): <3> # {cipher} <4> cfg = make_default_config({cipher['Encrypted Texts']['EncryptedText']}) <5> cfg["debug"] = "TRACE" <6> result = main(cfg) <7> <8> assert result["IsPlaintext?"] == True <9> """ <10>
===========unchanged ref 0=========== at: tests.generate_tests.test_generator randomString(stringLength) ===========changed ref 0=========== # module: tests.generate_tests class test_generator: def make_test_true_template(self, cipher): id = self.randomString(8) return f""" def test_{cipher['Encrypted Texts']['CipherUsed']}_{id}(): # {cipher} + res = ciphey.main('''{cipher['Encrypted Texts']['EncryptedText']}''') - res = ciphey.main('{cipher['Encrypted Texts']['EncryptedText']}') assert(res == {cipher['Encrypted Texts']['PlainText']}) """
ciphey.neuralNetworkMod.nn/NeuralNetwork.__init__
Modified
Ciphey~Ciphey
bce18192302578215561a73ff6304942f0e82fbc
Deleted Useless stuff
<2>:<del> script_dir = os.path.dirname(__file__) <3>:<del> file_path = os.path.join(script_dir, "NeuralNetworkModel.model") <4>:<add> # self.MODEL = load_model("cipher_detector.h5") <del> self.MODEL = load_model(file_path) <5>:<add> self.MODEL = load_model(cipheydists.get_model("cipher_detector"))
# module: ciphey.neuralNetworkMod.nn class NeuralNetwork: def __init__(self): <0> self.CATEGORIES = ["sha1", "md5", "sha256", "sha512", "caeser", "plaintext"] <1> self.CATEGORIES = [1, 2, 3, 4, 5, 6] <2> script_dir = os.path.dirname(__file__) <3> file_path = os.path.join(script_dir, "NeuralNetworkModel.model") <4> self.MODEL = load_model(file_path) <5> <6> self.mh = mh.mathsHelper() <7>
===========unchanged ref 0=========== at: mathsHelper mathsHelper() ===========changed ref 0=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: - - def decryptMessage(self, key, message): - return self.translateMessage(key, message, "decrypt") - ===========changed ref 1=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def get_item_at_index_zero(items): - """Gets the item at index 0 from an iterable""" - return items[0] - ===========changed ref 2=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def check_equal(a) -> bool: - """checks if all items in an iterable are the same. - - https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical - - Args: - a -> an iterable - - Returns: - Returns boolean. - - """ - return a.count(a[0]) == len(a) - ===========changed ref 3=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def sort_dictionary(dictionary: dict) -> dict: - """Sorts a dictionary. - - Uses OrderedDict to sort a dictionary. - - Args: - dictionary -> the dictionary to sort. - - Returns: - Returns the dictionary, but sorted. - - """ - ret = dict(OrderedDict(sorted(dictionary.items()))) - logger.debug( - f"The old dictionary was {dictionary} and I am sorting it to {ret}" - ) - return ret - ===========changed ref 4=========== # module: ciphey.mathsHelper class mathsHelper: - - def english_freq_match_score(self, message: str) -> int: - """Return number of mathces in the string - - Return the number of matches that the string in the message - parameter has when its letter frequency is compared to English - letter frequency. A "match" is how many of its six most frequent - and six least frequent letters is among the six most frequent and - six least frequent letters for English. - - Args: - message -> message to get freq match of - - Returns: - int, how many matches for the most common letters / least common letters. - - """ - - freqOrder = self.get_frequency_order(message) - - matchScore = 0 - # Find how many matches for the six most common letters there are: - for commonLetter in self.ETAOIN[:6]: - if commonLetter in freqOrder[:6]: - matchScore += 1 - # Find how many matches for the six least common letters there are: - for uncommonLetter in self.ETAOIN[-6:]: - if uncommonLetter in freqOrder[-6:]: - matchScore += 1 - - return matchScore - ===========changed ref 5=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def find_mod_inverse(a: int, m: int) -> int: - """Return the modular inverse of a % m. - - Which is the number x such that a*x % m = 1. Calculated using the Extended Euclidean Algorithm. - - Args: - a -> num 1 - m -> num 2 - - Returns: - Returns modular inverse(u1, m) - - """ - # Return the modular inverse of a % m, which is - # the number x such that a*x % m = 1 - - if gcd(a, m) != 1: - return None # No mod inverse exists if a & m aren't relatively prime. - - # Calculate using the Extended Euclidean Algorithm: - u1, u2, u3 = 1, 0, a - v1, v2, v3 = 0, 1, m - while v3 != 0: - q = u3 // v3 # Note that // is the integer division operator - v1, v2, v3, u1, u2, u3 = ( - (u1 - q * v1), - (u2 - q * v2), - (u3 - q * v3), - v1, - v2, - v3, - ) - return u1 % m - ===========changed ref 6=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: - - def translateMessage(self, key, message, mode): - translated = [] # Stores the encrypted/decrypted message string. - - keyIndex = 0 - key = key.upper() - - for symbol in message: # Loop through each symbol in message. - num = self.LETTERS.find(symbol.upper()) - if num != -1: # -1 means symbol.upper() was not found in LETTERS. - if mode == "encrypt": - num += self.LETTERS.find(key[keyIndex]) # Add if encrypting. - elif mode == "decrypt": - num -= self.LETTERS.find(key[keyIndex]) # Subtract if decrypting. - - num %= len(self.LETTERS) # Handle any wraparound. - - # Add the encrypted/decrypted symbol to the end of translated: - if symbol.isupper(): - translated.append(self.LETTERS[num]) - elif symbol.islower(): - translated.append(self.LETTERS[num].lower()) - - keyIndex += 1 # Move to the next letter in the key. - if keyIndex == len(key): - keyIndex = 0 - else: - # Append the symbol without encrypting/decrypting. - translated.append(symbol) - - return "".join(translated) -
ciphey.Decryptor.Encoding.bases/Bases.decrypt
Modified
Ciphey~Ciphey
bce18192302578215561a73ff6304942f0e82fbc
Deleted Useless stuff
<6>:<add> self.base85(text),
# module: ciphey.Decryptor.Encoding.bases class Bases: def decrypt(self, text: str): <0> logger.debug("Attempting base decoding") <1> <2> bases = [ <3> self.base32(text), <4> self.base16(text), <5> self.base64(text), <6> ] <7> for answer in bases: <8> try: <9> if answer["IsPlaintext?"]: <10> # good answer <11> logger.debug(f"Returning true for {answer}") <12> return answer <13> except TypeError: <14> continue <15> # Base85 <16> # if nothing works, it has failed. <17> return self.badRet() <18>
===========unchanged ref 0=========== at: ciphey.Decryptor.Encoding.bases.Bases base64(text: str) base32(text: str) base16(text: str) base85(text: str) ===========changed ref 0=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: - - def decryptMessage(self, key, message): - return self.translateMessage(key, message, "decrypt") - ===========changed ref 1=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def get_item_at_index_zero(items): - """Gets the item at index 0 from an iterable""" - return items[0] - ===========changed ref 2=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def check_equal(a) -> bool: - """checks if all items in an iterable are the same. - - https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical - - Args: - a -> an iterable - - Returns: - Returns boolean. - - """ - return a.count(a[0]) == len(a) - ===========changed ref 3=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def sort_dictionary(dictionary: dict) -> dict: - """Sorts a dictionary. - - Uses OrderedDict to sort a dictionary. - - Args: - dictionary -> the dictionary to sort. - - Returns: - Returns the dictionary, but sorted. - - """ - ret = dict(OrderedDict(sorted(dictionary.items()))) - logger.debug( - f"The old dictionary was {dictionary} and I am sorting it to {ret}" - ) - return ret - ===========changed ref 4=========== # module: ciphey.neuralNetworkMod.nn class NeuralNetwork: def __init__(self): self.CATEGORIES = ["sha1", "md5", "sha256", "sha512", "caeser", "plaintext"] self.CATEGORIES = [1, 2, 3, 4, 5, 6] - script_dir = os.path.dirname(__file__) - file_path = os.path.join(script_dir, "NeuralNetworkModel.model") + # self.MODEL = load_model("cipher_detector.h5") - self.MODEL = load_model(file_path) + self.MODEL = load_model(cipheydists.get_model("cipher_detector")) self.mh = mh.mathsHelper() ===========changed ref 5=========== # module: ciphey.mathsHelper class mathsHelper: - - def english_freq_match_score(self, message: str) -> int: - """Return number of mathces in the string - - Return the number of matches that the string in the message - parameter has when its letter frequency is compared to English - letter frequency. A "match" is how many of its six most frequent - and six least frequent letters is among the six most frequent and - six least frequent letters for English. - - Args: - message -> message to get freq match of - - Returns: - int, how many matches for the most common letters / least common letters. - - """ - - freqOrder = self.get_frequency_order(message) - - matchScore = 0 - # Find how many matches for the six most common letters there are: - for commonLetter in self.ETAOIN[:6]: - if commonLetter in freqOrder[:6]: - matchScore += 1 - # Find how many matches for the six least common letters there are: - for uncommonLetter in self.ETAOIN[-6:]: - if uncommonLetter in freqOrder[-6:]: - matchScore += 1 - - return matchScore - ===========changed ref 6=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def find_mod_inverse(a: int, m: int) -> int: - """Return the modular inverse of a % m. - - Which is the number x such that a*x % m = 1. Calculated using the Extended Euclidean Algorithm. - - Args: - a -> num 1 - m -> num 2 - - Returns: - Returns modular inverse(u1, m) - - """ - # Return the modular inverse of a % m, which is - # the number x such that a*x % m = 1 - - if gcd(a, m) != 1: - return None # No mod inverse exists if a & m aren't relatively prime. - - # Calculate using the Extended Euclidean Algorithm: - u1, u2, u3 = 1, 0, a - v1, v2, v3 = 0, 1, m - while v3 != 0: - q = u3 // v3 # Note that // is the integer division operator - v1, v2, v3, u1, u2, u3 = ( - (u1 - q * v1), - (u2 - q * v2), - (u3 - q * v3), - v1, - v2, - v3, - ) - return u1 % m - ===========changed ref 7=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: - - def translateMessage(self, key, message, mode): - translated = [] # Stores the encrypted/decrypted message string. - - keyIndex = 0 - key = key.upper() - - for symbol in message: # Loop through each symbol in message. - num = self.LETTERS.find(symbol.upper()) - if num != -1: # -1 means symbol.upper() was not found in LETTERS. - if mode == "encrypt": - num += self.LETTERS.find(key[keyIndex]) # Add if encrypting. - elif mode == "decrypt": - num -= self.LETTERS.find(key[keyIndex]) # Subtract if decrypting. - - num %= len(self.LETTERS) # Handle any wraparound. - - # Add the encrypted/decrypted symbol to the end of translated: - if symbol.isupper(): - translated.append(self.LETTERS[num]) - elif symbol.islower(): - translated.append(self.LETTERS[num].lower()) - - keyIndex += 1 # Move to the next letter in the key. - if keyIndex == len(key): - keyIndex = 0 - else: - # Append the symbol without encrypting/decrypting. - translated.append(symbol) - - return "".join(translated) -
ciphey.Decryptor.Encoding.bases/Bases._dispatch
Modified
Ciphey~Ciphey
bce18192302578215561a73ff6304942f0e82fbc
Deleted Useless stuff
<15>:<add> except: <add> logger.trace("Failed to decode base") <add> result = None
# module: ciphey.Decryptor.Encoding.bases class Bases: def _dispatch(self, decoder: Callable[[str], bytes], text: str, cipher: str): <0> logger.trace("Attempting base64") <1> result = None <2> try: <3> result = decoder(text) <4> # yeet turning b strings into normal stringy bois <5> result = result.decode("utf-8") <6> except UnicodeDecodeError as e: <7> logger.trace("Bad unicode") <8> result = None <9> except binascii.Error as e: <10> logger.trace("binascii error") <11> result = None <12> except ValueError: <13> logger.trace("Failed to decode base") <14> result = None <15> <16> if result is not None and self.lc.checkLanguage(result): <17> logger.debug(f"Bases successful, returning {result}") <18> return self.goodRet(result, cipher=cipher) <19> else: <20> return self.badRet() <21>
===========unchanged ref 0=========== at: binascii Error(*args: object) at: ciphey.Decryptor.Encoding.bases.Bases.__init__ self.lc = lc at: ciphey.LanguageChecker.brandon.Brandon wordlist: set checkLanguage(text: str) -> bool at: typing Callable = _CallableType(collections.abc.Callable, 2) ===========changed ref 0=========== # module: ciphey.Decryptor.Encoding.bases class Bases: def decrypt(self, text: str): logger.debug("Attempting base decoding") bases = [ self.base32(text), self.base16(text), self.base64(text), + self.base85(text), ] for answer in bases: try: if answer["IsPlaintext?"]: # good answer logger.debug(f"Returning true for {answer}") return answer except TypeError: continue # Base85 # if nothing works, it has failed. return self.badRet() ===========changed ref 1=========== # module: ciphey.Decryptor.basicEncryption.vigenere class Vigenere: - - def decryptMessage(self, key, message): - return self.translateMessage(key, message, "decrypt") - ===========changed ref 2=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def get_item_at_index_zero(items): - """Gets the item at index 0 from an iterable""" - return items[0] - ===========changed ref 3=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def check_equal(a) -> bool: - """checks if all items in an iterable are the same. - - https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical - - Args: - a -> an iterable - - Returns: - Returns boolean. - - """ - return a.count(a[0]) == len(a) - ===========changed ref 4=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def sort_dictionary(dictionary: dict) -> dict: - """Sorts a dictionary. - - Uses OrderedDict to sort a dictionary. - - Args: - dictionary -> the dictionary to sort. - - Returns: - Returns the dictionary, but sorted. - - """ - ret = dict(OrderedDict(sorted(dictionary.items()))) - logger.debug( - f"The old dictionary was {dictionary} and I am sorting it to {ret}" - ) - return ret - ===========changed ref 5=========== # module: ciphey.neuralNetworkMod.nn class NeuralNetwork: def __init__(self): self.CATEGORIES = ["sha1", "md5", "sha256", "sha512", "caeser", "plaintext"] self.CATEGORIES = [1, 2, 3, 4, 5, 6] - script_dir = os.path.dirname(__file__) - file_path = os.path.join(script_dir, "NeuralNetworkModel.model") + # self.MODEL = load_model("cipher_detector.h5") - self.MODEL = load_model(file_path) + self.MODEL = load_model(cipheydists.get_model("cipher_detector")) self.mh = mh.mathsHelper() ===========changed ref 6=========== # module: ciphey.mathsHelper class mathsHelper: - - def english_freq_match_score(self, message: str) -> int: - """Return number of mathces in the string - - Return the number of matches that the string in the message - parameter has when its letter frequency is compared to English - letter frequency. A "match" is how many of its six most frequent - and six least frequent letters is among the six most frequent and - six least frequent letters for English. - - Args: - message -> message to get freq match of - - Returns: - int, how many matches for the most common letters / least common letters. - - """ - - freqOrder = self.get_frequency_order(message) - - matchScore = 0 - # Find how many matches for the six most common letters there are: - for commonLetter in self.ETAOIN[:6]: - if commonLetter in freqOrder[:6]: - matchScore += 1 - # Find how many matches for the six least common letters there are: - for uncommonLetter in self.ETAOIN[-6:]: - if uncommonLetter in freqOrder[-6:]: - matchScore += 1 - - return matchScore - ===========changed ref 7=========== # module: ciphey.mathsHelper class mathsHelper: - - @staticmethod - def find_mod_inverse(a: int, m: int) -> int: - """Return the modular inverse of a % m. - - Which is the number x such that a*x % m = 1. Calculated using the Extended Euclidean Algorithm. - - Args: - a -> num 1 - m -> num 2 - - Returns: - Returns modular inverse(u1, m) - - """ - # Return the modular inverse of a % m, which is - # the number x such that a*x % m = 1 - - if gcd(a, m) != 1: - return None # No mod inverse exists if a & m aren't relatively prime. - - # Calculate using the Extended Euclidean Algorithm: - u1, u2, u3 = 1, 0, a - v1, v2, v3 = 0, 1, m - while v3 != 0: - q = u3 // v3 # Note that // is the integer division operator - v1, v2, v3, u1, u2, u3 = ( - (u1 - q * v1), - (u2 - q * v2), - (u3 - q * v3), - v1, - v2, - v3, - ) - return u1 % m -