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 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 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 remove_contact(index): contacts = db_get('contacts') temp_contact = copy.deepcopy(contacts[index]) del contacts[index] file_name = db_get('default_wallet') key = db_get('default_wallet_key') AESCipher.decrypt_file(key, file_name, file_name + '.dec') with open(file_name + '.dec') as data_file: my_read = data_file.read() data_file.close() os.remove(file_name + '.dec') try: data = json.loads(my_read) except: return 'Could not add contact\n' if 'seed' in data.keys(): data['contacts'] = contacts else: return 'Could not add contact\n' data_file = open(db_get('default_wallet'), 'w') data_file.write(json.dumps(data)) data_file.close() AESCipher.encrypt_into(key, file_name) db_put('contacts', contacts) return 'Removed contact \nName: ' + temp_contact[0] + '\nAddress: ' + temp_contact[1]
def add_contact(contact): if not valid_address(contact[1]): return 'Address is not valid\n' contacts = db_get('contacts') contact_json = {'name': contact[0], 'address': contact[1]} contacts.append(contact_json) file_name = db_get('default_wallet') key = db_get('default_wallet_key') AESCipher.decrypt_file(key, file_name, file_name + '.dec') with open(file_name + '.dec') as data_file: my_read = data_file.read() data_file.close() os.remove(file_name + '.dec') try: data = json.loads(my_read) except: return 'Could not add contact\n' if 'seed' in data.keys(): data['contacts'] = contacts else: return 'Could not add contact\n' data_file = open(db_get('default_wallet'), 'w') data_file.write(json.dumps(data)) data_file.close() AESCipher.encrypt_into(key, file_name) db_put('contacts', contacts) return 'Added contact \nName: ' + contact[0] + '\nAddress: ' + contact[1]
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 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 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 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 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_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 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 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 _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 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 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 __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 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 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 create_new_wallet(wallet_name, key, seed=None, contacts=[]): if seed == None: seed = generate_seed() print ":".join("{:02x}".format(ord(c)) for c in key) data = {} data['seed'] = seed data['contacts'] = contacts if not os.path.exists(custom.wallets_dir): os.makedirs(custom.wallets_dir) wallet_name = os.path.join(custom.wallets_dir, str(wallet_name)) f = open(wallet_name, 'w') f.write(json.dumps(data)) f.close() AESCipher.encrypt_into(key, wallet_name) return wallet_name
def loadPasswordList_UI(self): self.readPasswords() self.ids.password_list.clear_widgets() cipher = AESCipher("nv93h50sk1zh508v"); for entry in self.passwordList: 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.bind(on_release=self.onPasswordButtonClick) self.ids.password_list.add_widget(passwordBtn)
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(): 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 send_message(self, contact, message): print("sending message " + message + " to contact " + contact + ".") if self.contacts.get(contact) is not None: key = self.contacts.get(contact) enc = aes.encrypt(key, message) self.sender.sendto(enc, (contact, self.port)) else: print( "Unable to send message: AES key was not established successfully." )
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 __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 read_wallet(file_name, key): wallet = {} wallet['valid'] = False file_name = os.path.join(custom.wallets_dir, str(file_name)) try: open(file_name) except: wallet['message'] = 'Wallet file could not be read' return wallet if not key: wallet['message'] = 'You have to enter a password to open the wallet' return wallet AESCipher.decrypt_file(key, file_name, file_name + '.dec') with open(file_name + '.dec') as data_file: my_read = data_file.read() data_file.close() os.remove(file_name + '.dec') try: data = json.loads(my_read) except: wallet['message'] = 'There is a problem with encryption or wallet file is corrupted!' return wallet if 'seed' not in data: wallet['message'] = 'Wallet file has missing arguments(seed)!' else: wallet['valid'] = True wallet['seed'] = data['seed'] if 'contacts' not in data.keys(): wallet['contacts'] = [] else: wallet['contacts'] = data['contacts'] return wallet
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 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 process_new_contact(self, message, client_address): print("User " + client_address + " is requesting a conversation") client_pub = pickle.loads(message) print("Generating a random key for AES") key = aes.get_random_key() print("key: " + str(key)) self.contacts[client_address] = key print("Adding user " + client_address + " to contacts.") enc_key = client_pub.encrypt(key, 32)[0] print("Encrypting key with user's public key.") print("Sending encrypted key to user.") self.sender.sendto(enc_key, (client_address, self.port)) self.controller.new_contact2(client_address)
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')
from hashlib import sha256 from itertools import product from string import printable ciphertext = open('flag.encrypted', 'rb').read() printable = printable[:-5] password = "" for i in range(4): print("round {}".format(i + 1)) possibilities = [] for i,j in product(range(256), repeat=2): c1, c2 = chr(i), chr(j) if c1 not in printable or c2 not in printable: continue key = sha256(chr(i) + chr(j)).digest() cipher = AESCipher(key) dec = cipher.decrypt(ciphertext) n = ord(dec[-1]) if n < 32 and all(i == dec[-1] for i in dec[-n:]): print('padding length: {}'.format(n)) possibilities.append((n, chr(i) + chr(j), dec)) _, key, ciphertext = sorted(possibilities, reverse=True)[0] ciphertext = AESCipher._unpad(ciphertext) password = key + password print('found bytes: {}'.format(key)) with open('flag.dec', 'wb') as f: f.write(ciphertext) print(password)