示例#1
0
 def test_caesar_yes(self):
     model = NeuralNetwork()
     result = model.predictnn(
         "bcpvu up qvu ifs cpplt bxbz, cvu jotufbe tif qvmmfe")
     numpy.set_printoptions(suppress=True)
     result = numpy.argmax(result)
     self.assertEqual(result, 4)
示例#2
0
 def test_sha512_yes(self):
     model = NeuralNetwork()
     result = model.predictnn(
         "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"
     )
     numpy.set_printoptions(suppress=True)
     result = numpy.argmax(result)
     self.assertEqual(result, 3)
示例#3
0
 def test_english_yes(self):
     """Checks to see if it returns True (it should)"""
     model = NeuralNetwork()
     result = model.predictnn(
         "bcpvu up qvu ifs cpplt bxbz, cvu jotufbe tif qvmmfe")
     numpy.set_printoptions(suppress=True)
     result = numpy.argmax(result)
     self.assertEqual(result, 4)
示例#4
0
 def __init__(self, text, grep=False, cipher=False, debug=False):
     if not debug:
         logger.remove()
     # general purpose modules
     self.ai = NeuralNetwork()
     self.lc = lc.LanguageChecker()
     self.mh = mh.mathsHelper()
     # the one bit of text given to us to decrypt
     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 = grep
     self.cipher = cipher
     self.console = Console()
     self.probability_distribution: dict = {}
     self.what_to_choose: dict = {}
示例#5
0
 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.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.lc)
     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 = {}
示例#6
0
class Ciphey:
    config = dict()
    params = dict()

    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.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.lc)
        self.encoding = EncodingParent(self.lc)
        self.level: int = 1

        self.config = config

        self.console = Console()
        self.probability_distribution: dict = {}
        self.what_to_choose: dict = {}

    def decrypt(self) -> Optional[Dict]:
        """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!")
            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],
                "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:
                    # this should turn off hashing functions if offline mode is turned on
                    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.config["grep"]:
            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

    def produceprobtable(self, prob_table) -> None:
        """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 = {
            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

    def one_level_of_decryption(self) -> Optional[dict]:
        """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.config["grep"]:
            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

    def decrypt_normal(self, bar=None) -> Optional[dict]:
        """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)
        # 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.config["info"]:
                        logger.trace("Self.cipher_info runs")
                        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 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
示例#7
0
 def test_md5_yes(self):
     model = NeuralNetwork()
     result = model.predictnn("5d41402abc4b2a76b9719d911017c592")
     numpy.set_printoptions(suppress=True)
     result = numpy.argmax(result)
     self.assertEqual(result, 1)
示例#8
0
 def test_sha1_yes(self):
     model = NeuralNetwork()
     result = model.predictnn("6D32263A85C7846D70439026B75758C9FC31A9B7")
     numpy.set_printoptions(suppress=True)
     result = numpy.argmax(result)
     self.assertEqual(result, 0)