Exemplo n.º 1
0
    def setup_session(self):
        """Creates instances

        This method is called when the game is first started.
        It will create instances for players, map generators
        and servers.

        15 servers instances will be created
        """
        self.player_1 = Hacker()
        self.player_2 = Hacker()
        self.servers = []
        for srv in range(15):
            self.servers.append(Servers(srv))
        self.wmap = Worldmap(self.servers)
Exemplo n.º 2
0
def main(cipher, rsa = 0):
    print(cipher)
    sender = Sender(cipher)
    receiver = Receiver(cipher)
    key = cipher.generate_keys()
    if rsa:
        sender.set_key(key[0])
        receiver.set_key(key[1])
    else:
        sender.set_key(key)
        receiver.set_key(key)
    message = "shady crypto"

    print("Key is: ", key)
    print("Plaintext: ", message)
    crypted = message = sender.operate_cipher(message)
    print("Cryptedtext : ", message)
    message = receiver.operate_cipher(message)
    print("Cryptedtext converted back to Plaintext: ", message)

    if cipher.verify("text hacking example", key):
        print("Cipher is verified")
    else:
        print("Cipher is invalid")

    if not rsa:
        hacker = Hacker()
        print("Hacker will hack this cryptedtext: ", crypted)
        hacked = hacker.operate_cipher(crypted, cipher)
        print("Message:", '"' + str(hacked[0]) + '"', "is hacked with Key:", hacked[1])
    print("\n"*2)
Exemplo n.º 3
0
def run_normal_cipher(cipher, message):
    """Sends a message using cipher"""
    sender = Sender(cipher)
    encrypted = sender.operate_cipher(message)

    receiver = Receiver(cipher)
    receiver.operate_cipher(encrypted)

    hacker = Hacker()
    hacker.brute_force(encrypted, cipher)
Exemplo n.º 4
0
 def __init__(self, charT):
     if charT == 'H':
         self.h = Hacker()
         self.charType = "Hacker"
     elif charT == 'W':
         self.h = Warrior()
         self.charType = "Warrior"
     self.maxHP = self.h.getHP()
     self.strength = self.h.getStr()
     self.defense = self.h.getDef()
Exemplo n.º 5
0
def verify_cipher(cipher_name, key_word=''):
    """ Main method to test ciphers """
    # Instantiate cipher
    cipher = None
    if cipher_name == 'caesar':
        cipher = Caesar()
    elif cipher_name == 'multiplication':
        cipher = Multiplication()
    elif cipher_name == 'affine':
        cipher = Affine()
    elif cipher_name == 'unbreakable':
        cipher = Unbreakable()
    elif cipher_name == 'rsa':
        cipher = RSA()
    else:
        raise Exception('Cipher name not recognised')

    print(('\nTesting %s cipher:\n' % cipher_name).upper())

    # Define sender and receiver
    sender = Sender(cipher)
    receiver = Receiver(cipher)

    # Distribute key(s)
    if cipher_name == 'unbreakable':
        encryption_key, decryption_key = cipher.generate_keys(key_word)
    else:
        encryption_key, decryption_key = cipher.generate_keys()
    sender.set_key(encryption_key)
    receiver.set_key(decryption_key)

    # Create message and send it
    message = "Hello world"
    # message = "aaaaaaaaaaa"
    sender.send(message, receiver)

    print("\nSender message:  ", sender.message)
    print("Sender encoded:  ", sender.encoded_message)
    print("Receiver encoded:", receiver.encoded_message)
    print("Receiver decoded:", receiver.message)

    hack = input('\nDo you want to try and hack this message? (y/n): ')
    if hack == 'y':
        hacker = Hacker(cipher)
        if cipher_name in ('caesar', 'multiplication'):
            hacker.hack_caesar_or_multiplication(sender.encoded_message)
        elif cipher_name == 'affine':
            hacker.hack_affine(sender.encoded_message)
        elif cipher_name == 'unbreakable':
            hacker.hack_unbreakable(sender.encoded_message)
        else:
            print('No can do :P')
Exemplo n.º 6
0
def main():
    s = Sender()
    r = Receiver()

    c = choose_cipher()
    if isinstance(c, RSA):
        s.set_cipher(c)
        r.set_cipher(c)
        operate_rsa(s, r)
    else:
        s.set_cipher(c)
        s.operate_cipher()
        print(s.get_encoded())

        r.set_cipher(c)
        r.set_key(s.get_key())
        r.set_encoded(s.get_encoded())

        r.operate_cipher()
        print(r.get_decoded())
        print(
            "**************************************************************************"
        )

        time.sleep(2)
        print("OH, NO!")
        time.sleep(0.5)
        print("A WILD HACKER APPEARED!!!")
        h = Hacker()
        h.set_key(s.get_key())
        time.sleep(1)
        print("Hacker found traces of a key...")
        h.set_encoded(s.get_encoded())
        time.sleep(1)
        print("Hacker found an encoded message...")
        h.set_dict(h.open_file())
        time.sleep(1)
        print("SHIT, he's started hacking!!!!!!")
        time.sleep(1)
        cracked = h.hack(h.encoded, s.get_cipher())
        if cracked:
            time.sleep(2)
            print("The hacker has successfully cracked your " + str(c) +
                  " cipher algorithm.\n\\end")
        else:
            time.sleep(2)
            print("You have successfully beaten the hacker!")
            time.sleep(1)
            print("Or maybe used some words not in the dictionary...")
Exemplo n.º 7
0
 def setup_session(self):
     self.player_1 = Hacker()
     self.player_2 = Hacker()
     for srv in range(15):
         self.servers.append(Servers(srv))
Exemplo n.º 8
0
print("Verified: " + str(algorithm.verify("verify text")))

"""

#Unbreakable
algorithm = Unbreakable()
sender = Sender(algorithm)
receiver = Receiver(algorithm)
algorithm.generate_keys(sender, receiver)
print("Keys: " + str(sender.get_key()) + " and " + str(receiver.get_key()))
encrypted = sender.operate_cipher("hello world")
print("Encrypted: " + encrypted)
decrypted = receiver.operate_cipher(encrypted)
print("Decrypted: " + decrypted)
print("Verified: " + str(algorithm.verify("verify text")))
hacker = Hacker()
hacker_result = hacker.operate_cipher(encrypted)
print("Hacked: " + hacker_result)
"""Affine
algorithm = Affine()
sender = Sender(algorithm)
receiver = Receiver(algorithm)
algorithm.generate_keys(sender, receiver)
print("Keys: " + str(sender.get_key()) + " and " + str(receiver.get_key()))
encrypted = sender.operate_cipher("hello world")
print("Encrypted: " + encrypted)
decrypted = receiver.operate_cipher(encrypted)
print("Decrypted: " + decrypted)
print("Verified: " + str(algorithm.verify("verify text")))
hacker = Hacker()
hacker_result = hacker.operate_cipher(encrypted)
Exemplo n.º 9
0
def main():
    # 5 - образующая по простому модулю 23
    G = 5
    P = 23
    print("Инициализируем простые числа")

    # если True, будем разводить Алису на деньги (почему не Боба? Алиса больше зарабатывает, в яндекс устроилась)
    mellori_is_active = True

    # класс для генерации простых чисел
    primer = Primer(10**4, 10**4 + 1000)

    print("Создаём людей и фразочки для них")
    alice = Person(
        G, P, primer, "Alice", {
            'Привет':
            'Привет, идём завтра в кино?',
            'Конечно!':
            'Вот и замечательно! Завтра встретимся, пока!',
            'Пока!':
            None,
            'Слушай, не, совсем беда, денег нема. Скинь 500 р на номер 88005553535':
            'Окей, ща...'
        })
    bob = Person(
        G, P, primer, "Bob", {
            'Привет, идём завтра в кино?': 'Конечно!',
            'Вот и замечательно! Завтра встретимся, пока!': 'Пока!',
            None: None
        })

    # вообще конечно великая хакер Меллори может в реалтайме читать сообщения и нужным образом править текст, но...
    # но в данном случае у нас робот, который лишь видит будущее, поэтому заранее знает, какие фразы надо поменять в сообщениях, чтобы развести Алису
    mellori = Hacker(
        G,
        P,
        primer,
        "Mellori", {
            'Конечно!':
            'Слушай, не, совсем беда, денег нема. Скинь 500 р на номер 88005553535',
            'Окей, ща...': 'Вот и замечательно! Завтра встретимся, пока!',
            None: None
        },
        multi_keys=["Alice", "Bob"])

    print("Bob начал общение с Alice")
    sent = bob.start_communication_with("Alice")

    # основной цикл общения. по сути всё, что проходит через цикл - то доступно всем, это интернет, короче, публичный wifi или хз что ещё
    while True:
        # провайдер у нас логирует всё, что проходит по сети
        print("{} => {} # {} => {}".format(sent[0], sent[1], sent[2], sent[3]))

        # если хакер подключился к сети, то здесь он смотрит и модифицирует данные
        if mellori_is_active:
            print("      <=> НАЧАТ ПЕРЕХВАТ <=>")
            print("        Перехвачено =>", sent)
            sent = mellori.read_data(sent)
            print("        Отправлено  =>", sent)
            print("      <=> ПЕРЕХВАТ ЗАВЕРШЁН <=>")

        # законопослушные граждане
        if sent[1] == "Alice":
            sent = alice.read_data(sent)
        elif sent[1] == "Bob":
            sent = bob.read_data(sent)
        time.sleep(2)

        if sent[3] is None:
            print("Сеанс завершён")
            break

    # спецслужбы пришли к Алисе и Бобу выяснить, как у Алисы 500 р увели, так что смотрим логи граждан
    print("###################################")
    print()
    print("Смотрим логи переписки Алисы:")
    for data in alice.log:
        print(data)
    print()
    print("Смотрим логи переписки Боба:")
    for data in bob.log:
        print(data)