def test_aes_ctr(comm, nb_tests): """ Test AES CTR """ failed = False cipher = AESCipher(comm.symm_key) for _ in range(nb_tests): string = random_string(random.randint(15, 40)) init_vector = random_string(16) comm.write_serial_string(f"{Opcodes.AES_CTR} {init_vector}{string}") arduino_solution = comm.read_serial() cipher.setCounterValue( int.from_bytes(bytes(init_vector, "utf-8"), byteorder="big")) python_solution = ''.join('{:02x}'.format(x) for x in cipher.encryptCTR(string)) if python_solution != arduino_solution: print( colored( f"✗ Failed with input string '{string}'! Python gives {python_solution} while the arduino gives {arduino_solution}", "red", attrs=["bold"])) failed = True if not failed: print( colored(f"✓ All {nb_tests} test succeeded!", 'green', attrs=["bold"]))
def naxos(): #Keypair generation #BOB# domain, bob_pub_key, bob_priv_key = ec.get_keypair() #connecting to a server conn = rpyc.connect("localhost", 18861, config={"allow_all_attrs": True}) c = conn.root alice_pub_key = c.exchange_pubkey(bob_pub_key) print 'Alice pub key', alice_pub_key bob_esk = random.getrandbits(32) #32 bitowy ciag losowy G = domain.P #nasz publiczny punkt na krzywej #exch_bob H1(esk_B, sk_B) exch_bob = hashfun.sha(hashfun.concat(bob_esk, bob_priv_key.a)) exch_alice = c.exchange(G * exch_bob) S0 = alice_pub_key.Q * exch_bob #punkt S1 = (exch_alice) * bob_priv_key.a #punkt S2 = (exch_alice) * exch_bob session_key = hashfun.sha(hashfun.concat(S0.x.n, S1.x.n, S2.x.n)) print 'Session key:', session_key #AES PART print "Encoding AES message [Sample message]..." ac = AESCipher(session_key) enc = ac.encrypt('Sample message') print "Sending encrypted message [%s]..." % enc c.decrypt(enc)
def naxos(): #Keypair generation #BOB# domain, bob_pub_key, bob_priv_key = ec.get_keypair() #connecting to a server conn = rpyc.connect("localhost", 18861, config = {"allow_all_attrs" : True}) c = conn.root alice_pub_key = c.exchange_pubkey(bob_pub_key) print 'Alice pub key', alice_pub_key bob_esk = random.getrandbits(32) #32 bitowy ciag losowy G = domain.P #nasz publiczny punkt na krzywej #exch_bob H1(esk_B, sk_B) exch_bob = hashfun.sha(hashfun.concat(bob_esk, bob_priv_key.a)) exch_alice = c.exchange(G * exch_bob) S0 = alice_pub_key.Q * exch_bob #punkt S1 = (exch_alice) * bob_priv_key.a #punkt S2 = (exch_alice) * exch_bob session_key = hashfun.sha(hashfun.concat(S0.x.n, S1.x.n, S2.x.n)) print 'Session key:', session_key #AES PART print "Encoding AES message [Sample message]..." ac = AESCipher(session_key) enc = ac.encrypt('Sample message') print "Sending encrypted message [%s]..." % enc c.decrypt(enc)
def aes_decrypt(self, client_id, client_secret, refresh_token): key = "sakura" inst = AESCipher(key) client_id = inst.decrypt(client_id) client_secret = inst.decrypt(client_secret) refresh_token = inst.decrypt(refresh_token) return client_id, client_secret, refresh_token
def diffie_hellman(): #BOB# domain, bob_pub_key, bob_priv_key = ec.get_keypair() conn = rpyc.connect("localhost", 18861, config = {"allow_public_attrs" : True}) c = conn.root #Agree upon a public key c.send_pub_key(bob_pub_key) alice_pub_key = c.get_pub_key() print "Alice:\n", alice_pub_key secret_bob = bob_priv_key.a * alice_pub_key.Q print "Sharing secret..." secret_alice = c.share_secret(secret_bob) print "Secrets:\nAlice: %s\nBob %s\n" % (secret_alice, secret_bob) print "Encoding AES message [Sample message]..." ac = AESCipher(secret_bob.x) enc = ac.encrypt('Sample message') print "Sending encrypted message [%s]..." % enc c.decrypt(enc)
def handle_client(sock, rsa): print('Waiting for a connection...') # Wait for a conneciton connection, client_address = sock.accept() try: # Receive the data print("Recieving....") cipher = connection.recv(2048) print("Message Received...") try: message = myDecrypt(rsa, cipher) print("Received as: {}".format(message)) #if not message.decode('utf-8').strip().isprintable(): # raise Exception("Not printable?") aes = AESCipher(getSessionKey(rsa, cipher)) msg = aes.encrypt(message.upper()) except: connection.sendall("Couldn't decrypt!".encode('utf-8')) else: print('decrypted msg is {}'.format(aes.decrypt(msg))) print('message is {}'.format(message)) connection.sendall(msg) finally: # Clean up the connection connection.close() return True
def diffie_hellman(): #BOB# domain, bob_pub_key, bob_priv_key = ec.get_keypair() conn = rpyc.connect("localhost", 18861, config={"allow_public_attrs": True}) c = conn.root #Agree upon a public key c.send_pub_key(bob_pub_key) alice_pub_key = c.get_pub_key() print "Alice:\n", alice_pub_key secret_bob = bob_priv_key.a * alice_pub_key.Q print "Sharing secret..." secret_alice = c.share_secret(secret_bob) print "Secrets:\nAlice: %s\nBob %s\n" % (secret_alice, secret_bob) print "Encoding AES message [Sample message]..." ac = AESCipher(secret_bob.x) enc = ac.encrypt('Sample message') print "Sending encrypted message [%s]..." % enc c.decrypt(enc)
def handle_client(sock, rsa): print('Waiting for a connection...') # Wait for a conneciton connection, client_address = sock.accept() try: # Receive the data cipher = connection.recv(2048) print("Message Received...") message = myDecrypt(rsa, cipher) print("length of Decrypted message : {}".format(len(message))) if message: print("Received as: {}".format(message)) # temp1 = int.from_bytes(message, 'big', signed = False)) aes = AESCipher(getSessionKey(rsa, cipher)) msg = aes.encrypt(message.upper()) connection.sendall(msg) else: connection.sendall("Couldn't decrypt!") finally: # Clean up the connection connection.close() return True
def registerUser(self, usr, pwd, enc): aes = AESCipher(pwd) usr = aes.encrypt(usr) c = self.conn.cursor() c.execute("INSERT INTO users(username, encoding) VALUES (?,?)", (usr,enc)) self.conn.commit() c.close()
def setUser(self, id_user, username, passphrase): aes = AESCipher(passphrase) username = aes.decrypt(username) if username: self.currentUser = id_user self.currentPassphrase = passphrase self.registerLog("Login") return username
def DecryptMsj(self,event): aes = AESCipher() try: encM = aes.DecryptMessage(self.msj.get(1.0, END),self.passKey.get()) self.cph.delete('1.0', END) self.cph.insert(tk.INSERT,encM) except Exception: messagebox.showinfo(message="binascii Error \n Enter an encrypted message")
def updateBook(self, id_book, title, detail): aes = AESCipher(self.currentPassphrase) title = aes.encrypt(title) detail = aes.encrypt(detail) c = self.conn.cursor() c.execute("UPDATE contact_book SET title=?, detail=? WHERE id_book=?", (title, detail, id_book)) self.conn.commit() c.close() self.registerLog("Contact book succesfully updated")
def brute_forced_key(self, public_key): is_key_proper = False while not is_key_proper: key = self.generate_random_key() aes = AESCipher() is_key_proper = aes.is_proper_key(public_key, key) if is_key_proper: # print('Brute forced key ', key) return key
def decrypt_result(key, iv, s): s = s.replace("'", "\"") obj = json.loads(s, encoding='utf-8') if "result" not in obj.keys(): return s cipher = AESCipher(key=key, iv=iv) decrypted = cipher.decrypt(bytes(obj["result"], encoding='utf-8')) obj["result"] = json.loads(decrypted) return json.dumps(obj)
def encrypt_result(key, iv, s): s = s.replace("'", "\"") obj = json.loads(s, encoding='utf-8') if "result" not in obj.keys(): return s result = json.dumps(obj["result"]) cipher = AESCipher(key=key, iv=iv) encrypted = cipher.encrypt(result) obj["result"] = encrypted.decode("utf-8") return json.dumps(obj)
def _myDecrypt(self): """ Decrypt the client message: AES key encrypted by the public RSA key of the server + message encrypted by the AES key """ messageEncrypted = self.cipher[256:] AESKey = self._getSessionKey() aes = AESCipher(AESKey) return aes.decrypt(messageEncrypted)
def getAllBooks(self): c = self.conn.cursor() c.execute("SELECT id_book, title, detail FROM contact_book WHERE id_user=?", (self.currentUser,)) agendas = [] for row in c: aes = AESCipher(self.currentPassphrase) agenda = [row[0], aes.decrypt(row[1]), aes.decrypt(row[2])] agendas.append(agenda) c.close() self.registerLog("Contact books succesfully retrieved from database") return agendas
def getAllLogs(self): c = self.conn.cursor() c.execute("SELECT id_log, event_timestamp, event_detail FROM logs WHERE event_user=?", \ (self.currentUser,)) logs = [] for row in c: aes = AESCipher(self.currentPassphrase) log = [row[0], aes.decrypt(row[1]), aes.decrypt(row[2])] logs.append(log) c.close() return logs
def updateNote(self, id_note, title, content, timestamp): aes = AESCipher(self.currentPassphrase) title = aes.encrypt(title) content = aes.encrypt(content) timestamp = aes.encrypt(timestamp) c = self.conn.cursor() c.execute("UPDATE notes SET title=?, content=?, note_timestamp=? WHERE id_note=?", \ (title,content,timestamp,id_note)) self.conn.commit() c.close() self.registerLog("Private note succesfully updated")
def myDecrypt(rsa, cipher): """ Decrypt the client message: AES key encrypted by the public RSA key of the server + message encrypted by the AES key """ messageEncrypted = cipher[256:] print('messageEncrypted...') print(binascii.hexlify(messageEncrypted)) AESKey = getSessionKey(rsa, cipher) aes = AESCipher(AESKey) return aes.decrypt(messageEncrypted)
def getAllNotes(self): c = self.conn.cursor() c.execute("SELECT id_note, title, content, note_timestamp FROM notes WHERE id_user=?", \ (self.currentUser,)) notes = [] for row in c: aes = AESCipher(self.currentPassphrase) note = [row[0], aes.decrypt(row[1]), aes.decrypt(row[2]), aes.decrypt(row[3])] notes.append(note) c.close() self.registerLog("Private notes successfully retrieved from database") return notes
def saveBook(self, title, detail): aes = AESCipher(self.currentPassphrase) title = aes.encrypt(title) detail = aes.encrypt(detail) c = self.conn.cursor() c.execute("INSERT INTO contact_book(title, detail, id_user) VALUES (?,?,?)", \ (title, detail, self.currentUser)) id_agenda = c.lastrowid self.conn.commit() c.close() self.registerLog("Contact book succesfully saved") return id_agenda
def registerLog(self, event_detail): self.connect() timestamp = datetime.datetime.now() timestamp = timestamp.strftime("%Y-%m-%d %H:%M:%S") aes = AESCipher(self.currentPassphrase) timestamp = aes.encrypt(timestamp) event_detail = aes.encrypt(event_detail) c = self.conn.cursor() c.execute("INSERT INTO logs(event_timestamp, event_user, event_detail) VALUES (?,?,?)", \ (timestamp, self.currentUser, event_detail)) self.conn.commit() c.close() self.close()
def saveNote(self, title, content, timestamp): aes = AESCipher(self.currentPassphrase) title = aes.encrypt(title) content = aes.encrypt(content) timestamp = aes.encrypt(timestamp) c = self.conn.cursor() c.execute("INSERT INTO notes(title, content, note_timestamp, id_user) VALUES (?,?,?,?)", \ (title,content,timestamp,self.currentUser)) id_note = c.lastrowid self.conn.commit() c.close() self.registerLog("Private note succesfully saved") return id_note
def generate_public_keys(self): aes_cipher = AESCipher() encrypted_messages = [] for i in range(2**self.security_parameter): message_to_be_encrypted = bitarray(self.build_message(i), 'big').tobytes() encryption_key = self.build_encryption_key() encryption_result = aes_cipher.encrypt(message_to_be_encrypted, encryption_key) # decrypted_message = aes_cipher.decrypt(encryption_result, encryption_key) # print(message_to_be_encrypted == decrypted_message, '\n') encrypted_messages.append(encryption_result) # print(self.keys) return encrypted_messages
def respond(self): number = random.randint(0, 2**self.security_parameter - 1) # print('random number ', number) public_key = self.public_keys[number] key = self.brute_forced_key(public_key) decryption_result = AESCipher().decrypt(public_key, key) message = bin(int(decryption_result.hex(), 16))[2:].zfill(256) message_key = message[self.security_parameter:-( 128 - self.security_parameter)] # print('Responding with encryption of message key ', Utils.string_of_bits_to_bytes(message_key)) # print(message) # print(message_key, len(message_key)) # print(number) # print(bin(int(decryption_result.hex(), 16))[2:].zfill(256)) return number, AESCipher().encrypt( self.message, Utils.string_of_bits_to_bytes(message_key))
def getAllContacts(self, id_book): c = self.conn.cursor() c.execute("SELECT id_contact, full_name, address, email, phone_one, phone_two, webpage, detail FROM contact WHERE id_book=?", \ (id_book,)) contacts = [] for row in c: aes = AESCipher(self.currentPassphrase) contact = [row[0], aes.decrypt(row[1]), aes.decrypt(row[2]), aes.decrypt(row[3]), aes.decrypt(row[4]), \ aes.decrypt(row[5]), aes.decrypt(row[6]), aes.decrypt(row[7])] contacts.append(contact) c.close() self.registerLog("Contacts from contact book succesfully retrieved from database") return contacts
def cipher(self): key = self.keyInput.get() # key length must 16 character if len(key) != 16: messagebox.showwarning("Warning", "Key must be 16 character") return return AESCipher(self.keyInput.get())
def EncryptFiles(self,event): aes = AESCipher() if(os.path.isfile(self.fichier) == True): if(self.theKey.get() != ""): out = aes.EncryptFile(self.theKey.get(),self.fichier) self.fin.delete('1.0', END) self.fin.insert(tk.INSERT,"File encryption .....\n") os.remove(self.fichier) self.fin.insert(tk.INSERT,"File encrypted.\n") self.fin.insert(tk.INSERT,"Close !\n OUTPUT : "+out) self.pas.delete('0',"end") self.fs.config(text="File Selected :") self.Updates() else: messagebox.showinfo(message="Key required \n Enter a key !") else: messagebox.showinfo(message="File Error \n This path is not valid !")
def myDecrypt(rsa, cipher): """ Decrypt the client message: AES key encrypted by the public RSA key of the server + message encrypted by the AES key """ messageEncrypted = cipher[256:] AESKey = getSessionKey(rsa, cipher) print() print("Server AES Key in binary") aeky = bin(int.from_bytes(AESKey, 'big', signed=False)) print(aeky) print('__________') print(len(aeky)) print("__________") aes = AESCipher(AESKey) return aes.decrypt(messageEncrypted)
def receive_msg(): with open('private.pem', 'rb') as f: privateKeyString = f.read() privateKey = load_private_key_string(privateKeyString) emessage = request.form['Message'] seed = request.form['Seed'] seed = decrypt_message(privateKey, seed) emessage = emessage.replace('-', '+') emessage = emessage.replace('_', '/') print seed print emessage obj = AESCipher(seed) finalmessage = obj.decrypt(emessage) print finalmessage d = json.loads(finalmessage) uuid = d['Uuid'] requestId = d['RequestId'] topic = d['Topic'] message = d['Message'] d1 = json.loads(message) intent_description = d1['Intent_Description'] deadline = d1['Deadline'] print uuid print requestId print topic print message userreq = UserReq(uuid, requestId, topic, message) db.session.add(userreq) db.session.commit() d2 = {} d2['Uuid'] = uuid d2['RequestId'] = requestId d2['Topic'] = topic d2['Deadline'] = deadline print "ok" result = requests.post('http://' + proxy_ip + ":" + proxy_port + '/receive/request/', data=json.dumps(d2)) print result publish_msg(mogrify(topic, d)) return "Intent Published"
async def on_message(message): #Ignore MSGs if they're not DMs #TODO implement end-to-end group chatting if message.author == bot.user or not isinstance(message.channel, discord.DMChannel): return #database['chats'][str(message.author.id)].append(message.content) if message.content.startswith("===KEYEXCH==="): # Perform a Diffie-Hellman key exchange print(f"Key exchange started with {message.author.name}") k2 = message.content.find("value:") df = DiffieHellman() k1 = df.generate_k() key = df.generate_full_key(k2) database['users'][str(message.author.id)]['key'] = df print("Key with user: "******" is ", database['users'][str(message.author.id)]['key'].key) await message.author.send(f"===KEYACK===\nvalue:{k1}") elif message.content.startswith("===KEYACK==="): value = message.content.find("value:") k2 = message.content[value+6:] df = database['users'][str(message.author.id)]['key'] df.generate_full_key(k2) database['users'][str(message.author.id)]['key'] = df print("Key with user: "******" is ", database['users'][str(message.author.id)]['key'].key) elif message.content.startswith("===MSG==="): # Recieve a message: content = message.content[9:] try: key = database['users'][str(message.author.id)]['key'].key aes = AESCipher( key ) decrypted = aes.decrypt(content) except: print("Error while decrypting message") return print(content) print(decrypted) # 0 - Sent by someone # 1 - Sent by you database['chats'][str(message.author.id)].append( [0, decrypted] )
def receive_msg(): with open('private.pem', 'rb') as f: privateKeyString = f.read() privateKey = load_private_key_string(privateKeyString) emessage = request.form['Message'] seed = request.form['Seed'] seed = decrypt_message(privateKey, seed) emessage = emessage.replace('-', '+') emessage = emessage.replace('_', '/') print seed print emessage obj = AESCipher(seed) finalmessage = obj.decrypt(emessage) print finalmessage d = json.loads(finalmessage) uuid = d['Uuid'] requestId = d['RequestId'] topic = d['Topic'] message = d['Message'] d1 = json.loads(message) intent_description = d1['Intent_Description'] deadline = d1['Deadline'] print uuid print requestId print topic print message userreq = UserReq(uuid, requestId, topic, message) db.session.add(userreq) db.session.commit() d2 = {} d2['Uuid'] = uuid d2['RequestId'] = requestId d2['Topic'] = topic d2['Deadline'] = deadline print "ok" result = requests.post('http://'+proxy_ip+":"+proxy_port+'/receive/request/', data=json.dumps(d2)) print result publish_msg(mogrify(topic, d)) return "Intent Published"
def query_run(id, database_id): """ Run a query against a specific database instance """ if config.enable_run_query: database = db.get_database_details(database_id) query = db.get_query_details(id) query_results = None query_results_cols = [] error = None # try and import the DB engine try: dbapi2 = __import__(config.database_engine) except ImportError as e: app.logger.error("Fatal error. Could not import DB engine.", exc_info=True) flash("Fatal error. Contact Administrator", "error") return redirect(url_for("index")) # try and make the connection and run the query try: if database.get("password"): crypt = AESCipher(config.flask_secret_key) password = crypt.decrypt(database.get("password")) else: password = None connect = dbapi2.connect(database=database.get("name"), host=database.get("hostname"), port=database.get("port"), user=database.get("user"), password=password) curse = connect.cursor() curse.execute(query["sql"]) query_results = curse.fetchall() # Assemble column names so the table makes sense for col in curse.description: query_results_cols.append(col.name) except dbapi2.ProgrammingError as e: # TODO: Exceptions don't seem to be standard in DB-API2, # so this will likely have to be checked against other # engines. The following works with psycopg2. if hasattr(e, "pgerror"): error = e.pgerror else: error = "There was an error with your query." except dbapi2.Error as e: if hasattr(e, "pgerror"): error = e.pgerror or e.message app.logger.error(error) else: error = e.msg app.logger.error(error) else: database = None query = None query_results = None query_results_cols = None error = None return render_template("run_query.html", run_enabled=config.enable_run_query, query=query, database=database, query_results=query_results, query_results_cols=query_results_cols, error=error)
def exposed_decrypt(self, msg): print 'Received hash. Printing message...' print msg ac = AESCipher(self.session_key)#secret_alice.x) dec = ac.decrypt(msg) print dec