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)
def get(self): self.response.headers['Content-type'] = 'text/plain' giver = hacker = Hacker.gql(""" WHERE username = :1 LIMIT 1 """, "p33").get() recipient = hacker = Hacker.gql(""" WHERE username = :1 LIMIT 1 """, "peevis").get() giver.givePoints(recipient, 50)
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)
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...")
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)
def main(): maker = URLMaker() urls = maker.urls(144250,145000) hacker = Hacker() with open("log.txt", "w") as a_file: hacker.set_file(a_file) hacker.set_urls(urls) hacker.hack()
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()
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')
def get(self): self.response.headers['Content-Type'] = 'text/json' query = Hacker.gql("ORDER BY points DESC LIMIT 50"); self.response.out.write("["); first = True for result in query: if (first == False): self.response.out.write(","); self.response.out.write(result.asJSON()) first = False self.response.out.write("]");
def get(self): session = get_current_session() if not session.is_active(): self.forceTwitter(); return username = session.get("username") if not username: session.terminate() self.forceTwitter(); return; hacker = Hacker.gql(""" WHERE username = :1 LIMIT 1 """, username).get() if not hacker: logging.error("Had a username but no hacker:" + username) session.terminate() self.forceTwitter(); return template_values = { 'username' : username, 'url_picture': hacker.picture, 'name' : hacker.name, 'points' : hacker.points, 'pool' : hacker.pool, 'internets' : hacker.internets, 'easterEggs' : hacker.easterEggs, 'hacks' : hacker.hacks } self.response.headers['Content-Type'] = 'text/html' path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values))
def setup_session(self): self.player_1 = Hacker() self.player_2 = Hacker() for srv in range(15): self.servers.append(Servers(srv))
def get(self): session = get_current_session() if session.is_active(): logger.info("Found a session") session.terminate() # the request_token from twitter request_token = self.request.get("oauth_token") request_token = urlunquote(request_token) # the OAuth verifier from twitter oauth_verifier = self.request.get("oauth_verifier") oauth_verifier = urlunquote(oauth_verifier) ss = SecretSquirrel() client = twitterauth.OAuthClient(ss.conKey, ss.conSec, ss.cbURL) auth_secret = memcache.get(client._get_memcache_auth_key(request_token)) if not auth_secret: result = twitterauth.AuthToken.gql(""" WHERE token = :1 LIMIT 1 """, request_token).get() if not result: logger.error("The auth token %s was not found in our db" % request_token) raise Exception, "Could not find Auth Token in database suck to be you" else: auth_secret = result.secret # now go back to twitter and exchange the request_token and oauth_verifier for an access_token and a token_secret response = client.make_request(client.access_url, token=request_token, secret=auth_secret, additional_params={"oauth_verifier": oauth_verifier}) result = client._extract_credentials(response) # Try to collect some information about this user from the service. user_info = client._lookup_user_info(result["token"], result["secret"]) if not user_info: return self.response.out.write("failed to get user_info") user_info.update(result) session = get_current_session() session['username'] = user_info['username'] username = user_info['username'] hacker = Hacker.gql(""" WHERE username = :1 LIMIT 1 """, username).get() if not hacker: logger.info("Making new hacker") hacker = Hacker() hacker.name = user_info["name"] hacker.token = user_info["token"] hacker.picture = user_info["picture"] hacker.secret = user_info["secret"] hacker.username = user_info["username"] hacker.points = 0 hacker.pool = 100 hacker.internets = 0 hacker.easterEggs = 0 hacker.hacks = 0 hacker.put() else: logger.info("Found me a hacker") #return self.response.out.write(user_info) return self.redirect("/")
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)
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)
def get(self): session = get_current_session() if not session.is_active(): self.forceTwitter(); return username = session.get("username") if not username: session.terminate() self.forceTwitter(); return; hacker = Hacker.gql(""" WHERE username = :1 LIMIT 1 """, username).get() if not hacker: logging.error("Had a username but no hacker:" + username) session.terminate() self.forceTwitter(); return self.response.headers['Content-Type'] = 'text/html' # logging.info("Calling out to twitter for ids") # https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name=twitterapi cursor = -1 ss = SecretSquirrel() client = twitterauth.OAuthClient(ss.conKey, ss.conSec, ss.cbURL) token = hacker.token secret = hacker.secret username = hacker.username ids = [] done = 0 while done == 0: idResponse = client.make_request("https://api.twitter.com/1/friends/ids.json", token=token, secret=secret, additional_params={"cursor": cursor, "screen_name": username}) status = idResponse.status_code # logging.info(status) if status != 200: return self.response.out.write("Return code wasn't 200 it was:" + str(status)) self.response.out.write(idResponse) data = json.loads(idResponse.content) # self.response.out.write(data) nextCursor = data['next_cursor'] if nextCursor == 0: done = 1; jIDS = data['ids'] if not jIDS: done = 1; continue else: ids.extend(jIDS) # self.response.out.write("Done with ids loop\n") # self.response.out.write("Found " + str(len(jIDS)) + " friend IDS\n") cursor = 0 lookupIDS = "" jidCount = len(jIDS) while cursor <= jidCount: li = 0 while li <= 99: try: tid = jIDS.pop() lookupIDS = lookupIDS + str(tid) + "," li = li + 1 cursor = cursor + 1 except: # logging.info("Stopped at " + str(li) + " count") li = 100 cursor = (jidCount + 1) # https://api.twitter.com/1/users/lookup.json?screen_name=twitterapi,twitter&include_entities=true fResponse = client.make_request("https://api.twitter.com/1/users/lookup.json", token=token, secret=secret, additional_params={"user_id": lookupIDS, "include_entities":"false"}, method="POST") status = fResponse.status_code if status != 200: return self.response.out.write("Return code wasn't 200 it was:" + str(status)) data = json.loads(fResponse.content) lookupIDS = "" for user in data: self.response.out.write("<p>") template_values = { 'id' : user['id'], 'pics' : user['profile_image_url_https'], 'pic' : user['profile_image_url'], 'screenName' : user['screen_name'], 'name' : user['name'], 'verified' : user['verified'], 'url' : user['url'], } path = os.path.join(os.path.dirname(__file__), 'user.html') self.response.out.write(template.render(path, template_values)) self.response.out.write("</p>") self.response.out.write("Done requesting friends info")