def shareFile(user, filename, usr_dest, permission): """Share function, allows a file to be shared with another user. The file with the AES used to encrypt the file to be shared is sent from the server, it is decrypted and encrypted with the target user's public key Security: - Sharing user's private key is used for decrypting file with AES key - Target user's public key is used for encrypting file with AES key - Sharing client receives no information from the other user except username and public key - All relevant information is kept client-side""" (username, session) = user.getInfo() message = { 'filename': filename, 'usrdstname': usr_dest, } messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex') params = {'data': messageToSend, 'username': username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request('https://localhost:8080/share', datagen, headers) data = urllib2.urlopen(resp) date = json.loads( security.decryptS_AES(data.info().getheader('data').decode('hex'), session.decode('hex'))) aes = date['aes'].decode('hex') pub_key = date['pubkey'].decode('hex') with open('PrivateKeys/Private_key_' + str(username), 'rb') as f: priv = security.importkey_RSA(f.read()) RsaAES = security.decrypt_RSA(priv, aes) tf = tempfile.NamedTemporaryFile(delete=True) security.encrypt_RSA(security.importkey_RSA(pub_key), RsaAES, tf) message = { 'filename': filename, 'usrdstname': usr_dest, 'filekey': tf.read().encode('hex'), 'permission': permission } messageToSend = security.encryptS_AES( json.dumps(message), session.decode('hex')).encode('hex') request = urllib2.Request('https://localhost:8080/shareFile') request.add_header('username', username) request.add_header('data', messageToSend) response = urllib2.urlopen(request) tf.close() print response.read() except urllib2.HTTPError as e: print str(e.code) + ': ' + e.reason print 'Currently, you are not a valid user!\nSafeBox Team'
def getShareUsers(self, **kwargs): """Server Side Get Share Users Get all the users that are available to share a file filtered by favourite user or normal user Security: Authenticate User Message""" if um.validUser(kwargs['username']): sessionKey = um.getSessionKey(kwargs['username']) usr_id = DBmodule.db_getUserID(kwargs['username']) data = json.loads( security.decryptS_AES(kwargs['data'].decode('hex'), sessionKey.decode('hex'))) filename = data['filename'] file_id = DBmodule.db_getFileId(usr_id, filename) access = DBmodule.db_getUsersWithFile(file_id) every = DBmodule.db_getAllUsers() fav = [ x for x in DBmodule.db_getPreviousUsersShared(usr_id) if x not in access ] fav += ['@@@@@'] fav += [ x for x in every if x not in fav and x != kwargs['username'] and x not in access ] return security.encryptS_AES( json.dumps(fav), sessionKey.decode('hex')).encode('hex') else: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team')
def getSharedWith(user, filename): """Function for getting the usernames that have a certain user's file being shared with them, handled server side since no security measures other than Authentication are needed""" register_openers().add_handler( urllib2.HTTPCookieProcessor(cookielib.CookieJar())) (username, session) = user.getInfo() message = {'filename': filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex') params = {'username': username, 'data': messageToSend} try: datagen, headers = multipart_encode(params) resp = urllib2.Request('https://localhost:8080/getSharedWith', datagen, headers) response = urllib2.urlopen(resp).read() users = (json.loads( security.decryptS_AES(response.decode('hex'), session.decode('hex')))) list_users = [x.encode('latin-1') for x in users] return list_users except urllib2.HTTPError as e: print str(e.code) + ': ' + e.reason print 'Currently, you are not a valid user!\nSafeBox Team' return []
def shareFile(user, filename, usr_dest, permission): """Share function, allows a file to be shared with another user. The file with the AES used to encrypt the file to be shared is sent from the server, it is decrypted and encrypted with the target user's public key Security: - Sharing user's private key is used for decrypting file with AES key - Target user's public key is used for encrypting file with AES key - Sharing client receives no information from the other user except username and public key - All relevant information is kept client-side""" (username, session) = user.getInfo() message = {"filename": filename, "usrdstname": usr_dest} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") params = {"data": messageToSend, "username": username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request("https://localhost:8080/share", datagen, headers) data = urllib2.urlopen(resp) date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex"))) aes = date["aes"].decode("hex") pub_key = date["pubkey"].decode("hex") with open("PrivateKeys/Private_key_" + str(username), "rb") as f: priv = security.importkey_RSA(f.read()) RsaAES = security.decrypt_RSA(priv, aes) tf = tempfile.NamedTemporaryFile(delete=True) security.encrypt_RSA(security.importkey_RSA(pub_key), RsaAES, tf) message = { "filename": filename, "usrdstname": usr_dest, "filekey": tf.read().encode("hex"), "permission": permission, } messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") request = urllib2.Request("https://localhost:8080/shareFile") request.add_header("username", username) request.add_header("data", messageToSend) response = urllib2.urlopen(request) tf.close() print response.read() except urllib2.HTTPError as e: print str(e.code) + ": " + e.reason print "Currently, you are not a valid user!\nSafeBox Team"
def download(filename, destination, privpath, user): """Download function, creates a temporary file to where the encrypted file is streamed to, then it is read chunk by chunk and decrypted. Security: - Authentication - File is decrypted with AES - hasher is created for File Integrity Control - Public key is accessed for decrypting the AES key - Private Key is accessed for verifying the file signature - All relevant information is kept client-side""" (username, session) = user.getInfo() message = {'filename': filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex') params = {'data': messageToSend, 'username': username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request('https://localhost:8080/download', datagen, headers) data = urllib2.urlopen(resp) fn = data.info().getheader('filename') date = json.loads( security.decryptS_AES(data.info().getheader('data').decode('hex'), session.decode('hex'))) aes = data.info().getheader('aes').decode('hex') iv = date['iv'].decode('hex') signature = date['sign'].decode('hex') with open(privpath, 'rb') as f: priv = security.importkey_RSA(f.read()) pub = security.importkey_RSA(getPubKey(username)) RsaAES = security.decrypt_RSA(priv, aes) decipher = security.getDecipher(iv, RsaAES) tf = tempfile.NamedTemporaryFile(delete=True) CHUNK = 16 * 1024 while True: chunk = data.read(CHUNK) if not chunk: break tf.write(chunk) tf.seek(0) hasher = security.Hasher() with open(os.path.join(str(destination), filename), 'wb') as out: security.decrypt_AES(decipher, tf, out, hasher) new = hasher.get() if security.verifyFile(pub, new, signature): print 'The File was not changed!' else: print 'The File was changed!' tf.close() except urllib2.HTTPError as e: print str(e.code) + ': ' + e.reason print 'Currently, you are not a valid user!\nSafeBox Team'
def diff(user, filename, privpath, filefp): """Function for getting the difference between a file in the server and a user file, works like download except no file is written. Security: - Authentication - File is decrypted with AES - hasher is created for File Integrity Control - Public key is accessed for decrypting the AES key - Private Key is accessed for verifying the file signature - All relevant information is kept client-side" """ (username, session) = user.getInfo() message = {'filename': filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex') params = {'data': messageToSend, 'username': username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request('https://localhost:8080/download', datagen, headers) data = urllib2.urlopen(resp) fn = data.info().getheader('filename') date = json.loads( security.decryptS_AES(data.info().getheader('data').decode('hex'), session.decode('hex'))) aes = data.info().getheader('aes').decode('hex') iv = date['iv'].decode('hex') signature = date['sign'].decode('hex') with open(privpath, 'rb') as f: priv = security.importkey_RSA(f.read()) pub = security.importkey_RSA(getPubKey(username)) RsaAES = security.decrypt_RSA(priv, aes) decipher = security.getDecipher(iv, RsaAES) tf = tempfile.NamedTemporaryFile(delete=True) out = tempfile.NamedTemporaryFile(delete=True) CHUNK = 16 * 1024 while True: chunk = data.read(CHUNK) if not chunk: break tf.write(chunk) tf.seek(0) hasher = security.Hasher() security.decrypt_AES(decipher, tf, out, hasher) out.seek(0) new = hasher.get() comp = open(filefp, 'rb').readlines() cenas = out.readlines() return diffchecker(comp, cenas) except urllib2.HTTPError as e: print str(e.code) + ': ' + e.reason print 'Currently, you are not a valid user!\nSafeBox Team'
def share(self, **kwargs): """Server Side Share Initial Commnunication Gets user access file by his user id from the File System and the user destination public key, from the DB, by his ID and sends the information to client Security: Authenticate User Message Concurrency control""" username = kwargs['username'] sessionKey = um.getSessionKey(username) if sessionKey != -1: try: data = json.loads( security.decryptS_AES(kwargs['data'].decode('hex'), sessionKey.decode('hex'))) file_name = data['filename'] usr_dst_name = data['usrdstname'] usr_id = DBmodule.db_getUserID(username) file_id = DBmodule.db_getFileId(usr_id, file_name) # Concurrent Access while (DBmodule.db_fileStatus(file_id) is True): time.sleep(2) status = DBmodule.db_fileInUse(file_id) # Verify if the user is valid and have access to the file if status and um.validUser( username) and DBmodule.db_filePermission( usr_id, file_id): destination = os.path.join('storage', str(file_id) + '.file') # Get User Access File with open(destination + '.key' + str(usr_id)) as f: aes = f.read() usr_dst_id = DBmodule.db_getUserID(usr_dst_name) pub_key = DBmodule.db_getUserPubKey(usr_dst_id) message = {'aes': aes, 'pubkey': pub_key} messageToSend = security.encryptS_AES( json.dumps(message), sessionKey.decode('hex')).encode('hex') cherrypy.response.headers['data'] = messageToSend statusF = DBmodule.db_fileNotInUse(file_id) if statusF is True: return "Okay" else: raise cherrypy.HTTPError( 408, 'Request Timeout! Please Try Again\nSafeBox Team') else: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team') except: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team') else: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team')
def download(filename, destination, privpath, user): """Download function, creates a temporary file to where the encrypted file is streamed to, then it is read chunk by chunk and decrypted. Security: - Authentication - File is decrypted with AES - hasher is created for File Integrity Control - Public key is accessed for decrypting the AES key - Private Key is accessed for verifying the file signature - All relevant information is kept client-side""" (username, session) = user.getInfo() message = {"filename": filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") params = {"data": messageToSend, "username": username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request("https://localhost:8080/download", datagen, headers) data = urllib2.urlopen(resp) fn = data.info().getheader("filename") date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex"))) aes = data.info().getheader("aes").decode("hex") iv = date["iv"].decode("hex") signature = date["sign"].decode("hex") with open(privpath, "rb") as f: priv = security.importkey_RSA(f.read()) pub = security.importkey_RSA(getPubKey(username)) RsaAES = security.decrypt_RSA(priv, aes) decipher = security.getDecipher(iv, RsaAES) tf = tempfile.NamedTemporaryFile(delete=True) CHUNK = 16 * 1024 while True: chunk = data.read(CHUNK) if not chunk: break tf.write(chunk) tf.seek(0) hasher = security.Hasher() with open(os.path.join(str(destination), filename), "wb") as out: security.decrypt_AES(decipher, tf, out, hasher) new = hasher.get() if security.verifyFile(pub, new, signature): print "The File was not changed!" else: print "The File was changed!" tf.close() except urllib2.HTTPError as e: print str(e.code) + ": " + e.reason print "Currently, you are not a valid user!\nSafeBox Team"
def diff(user, filename, privpath, filefp): """Function for getting the difference between a file in the server and a user file, works like download except no file is written. Security: - Authentication - File is decrypted with AES - hasher is created for File Integrity Control - Public key is accessed for decrypting the AES key - Private Key is accessed for verifying the file signature - All relevant information is kept client-side" """ (username, session) = user.getInfo() message = {"filename": filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") params = {"data": messageToSend, "username": username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request("https://localhost:8080/download", datagen, headers) data = urllib2.urlopen(resp) fn = data.info().getheader("filename") date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex"))) aes = data.info().getheader("aes").decode("hex") iv = date["iv"].decode("hex") signature = date["sign"].decode("hex") with open(privpath, "rb") as f: priv = security.importkey_RSA(f.read()) pub = security.importkey_RSA(getPubKey(username)) RsaAES = security.decrypt_RSA(priv, aes) decipher = security.getDecipher(iv, RsaAES) tf = tempfile.NamedTemporaryFile(delete=True) out = tempfile.NamedTemporaryFile(delete=True) CHUNK = 16 * 1024 while True: chunk = data.read(CHUNK) if not chunk: break tf.write(chunk) tf.seek(0) hasher = security.Hasher() security.decrypt_AES(decipher, tf, out, hasher) out.seek(0) new = hasher.get() comp = open(filefp, "rb").readlines() cenas = out.readlines() return diffchecker(comp, cenas) except urllib2.HTTPError as e: print str(e.code) + ": " + e.reason print "Currently, you are not a valid user!\nSafeBox Team"
def listMyFiles(self, **kwargs): """Server Side List Files List all the files that can be accessed by the user Security: Authenticate User Message""" if um.validUser(kwargs['username']): sessionKey = um.getSessionKey(kwargs['username']) usr_id = DBmodule.db_getUserID(kwargs['username']) message = DBmodule.db_listMyFilesInfo(usr_id) messageToSend = security.encryptS_AES( json.dumps(message), sessionKey.decode('hex')).encode('hex') return messageToSend else: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team')
def removeFile(user, filename): """Function for deleting a file, handled server side since no security measures other than Authentication are needed""" (username, session) = user.getInfo() try: message = {"filename": filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") request = urllib2.Request("https://localhost:8080/removeFile") request.add_header("username", username) request.add_header("data", messageToSend) response = urllib2.urlopen(request) except urllib2.URLError as e: print e.reason print "Currently, you are not a valid user!\nSafeBox Team"
def getPermission(user, filename): """ Function to ask for permission, to share a file """ (username, session) = user.getInfo() message = {"filename": filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") params = {"data": messageToSend, "username": username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request("https://localhost:8080/permission", datagen, headers) if urllib2.urlopen(resp).read() == "1": return 1 return 0 except: return 0
def removeFile(user, filename): """Function for deleting a file, handled server side since no security measures other than Authentication are needed""" (username, session) = user.getInfo() try: message = {'filename': filename} messageToSend = security.encryptS_AES( json.dumps(message), session.decode('hex')).encode('hex') request = urllib2.Request('https://localhost:8080/removeFile') request.add_header('username', username) request.add_header('data', messageToSend) response = urllib2.urlopen(request) except urllib2.URLError as e: print e.reason print 'Currently, you are not a valid user!\nSafeBox Team'
def getPermission(user, filename): """ Function to ask for permission, to share a file """ (username, session) = user.getInfo() message = {'filename': filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex') params = {'data': messageToSend, 'username': username} datagen, headers = multipart_encode(params) try: resp = urllib2.Request('https://localhost:8080/permission', datagen, headers) if urllib2.urlopen(resp).read() == "1": return 1 return 0 except: return 0
def getSharedWith(self, **kwargs): """Server Side GetSharedWith (Users) Get all the users that have access to a file Security: Authenticate User Message""" if um.validUser(kwargs['username']): sessionKey = um.getSessionKey(kwargs['username']) usr_id = DBmodule.db_getUserID(kwargs['username']) data = json.loads( security.decryptS_AES(kwargs['data'].decode('hex'), sessionKey.decode('hex'))) file_id = DBmodule.db_getFileId(usr_id, data['filename']) return security.encryptS_AES( json.dumps(DBmodule.db_getShareFileWith(usr_id, file_id)), sessionKey.decode('hex')).encode('hex') else: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team')
def unshare(user, filename, uns_username): """Function for unsharing a file with a user, since our approach for this problem is only removing the database entries, this function is handled server-side (Still a WIP and may be changed in the future)""" (username, session) = user.getInfo() message = {"filename": filename, "unshare": uns_username} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") params = {"username": username, "data": messageToSend} try: datagen, headers = multipart_encode(params) resp = urllib2.Request("https://localhost:8080/unShare", datagen, headers) response = urllib2.urlopen(resp).read() return response except urllib2.HTTPError as e: print str(e.code) + ": " + e.reason return "Currently, you are not a valid user!\nSafeBox Team"
def getSharedWith(user, filename): """Function for getting the usernames that have a certain user's file being shared with them, handled server side since no security measures other than Authentication are needed""" register_openers().add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) (username, session) = user.getInfo() message = {"filename": filename} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") params = {"username": username, "data": messageToSend} try: datagen, headers = multipart_encode(params) resp = urllib2.Request("https://localhost:8080/getSharedWith", datagen, headers) response = urllib2.urlopen(resp).read() users = json.loads(security.decryptS_AES(response.decode("hex"), session.decode("hex"))) list_users = [x.encode("latin-1") for x in users] return list_users except urllib2.HTTPError as e: print str(e.code) + ": " + e.reason print "Currently, you are not a valid user!\nSafeBox Team" return []
def unshare(user, filename, uns_username): """Function for unsharing a file with a user, since our approach for this problem is only removing the database entries, this function is handled server-side (Still a WIP and may be changed in the future)""" (username, session) = user.getInfo() message = { 'filename': filename, 'unshare': uns_username, } messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex') params = {'username': username, 'data': messageToSend} try: datagen, headers = multipart_encode(params) resp = urllib2.Request('https://localhost:8080/unShare', datagen, headers) response = urllib2.urlopen(resp).read() return response except urllib2.HTTPError as e: print str(e.code) + ': ' + e.reason return 'Currently, you are not a valid user!\nSafeBox Team'
def download(self, **kwargs): """Server Side Download a file Gets the ciphertext of the file by file ID, user access file by his user id from the File System and the IV from the DB Security: Authenticate User Message Concurrency control""" # Multipart aux function def read(i_file, chunk_size=16 * 1024): while True: ret = i_file.read(chunk_size) if not ret: break yield ret username = kwargs['username'] sessionKey = um.getSessionKey(username) if sessionKey != -1: try: data = json.loads( security.decryptS_AES(kwargs['data'].decode('hex'), sessionKey.decode('hex'))) usr_id = DBmodule.db_getUserID(username) filename = data['filename'] file_id = DBmodule.db_getFileId(usr_id, filename) # Concurrent Access while (DBmodule.db_fileStatus(file_id) is True): time.sleep(2) status = DBmodule.db_fileInUse(file_id) # Verify if the user is valid and have permission to access the file if (status and um.validUser(username) and DBmodule.db_filePermission(usr_id, file_id)): destination = os.path.join('storage', str(file_id) + '.file') # Get User Access File with open(destination + '.key' + str(usr_id)) as f: aes = f.read() iv = DBmodule.db_getFileIV(file_id).encode( 'latin-1').encode('hex') sign = DBmodule.db_getFileHash(file_id) message = {'iv': iv, 'sign': sign} messageToSend = security.encryptS_AES( json.dumps(message), sessionKey.decode('hex')).encode('hex') cherrypy.response.headers['data'] = messageToSend cherrypy.response.headers['aes'] = aes statusF = DBmodule.db_fileNotInUse(file_id) if statusF is True: return read(open(destination, 'rb')) else: raise cherrypy.HTTPError( 408, 'Request Timeout! Please Try Again\nSafeBox Team') else: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team') except: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team') else: raise cherrypy.HTTPError( 401, 'Currently, you are not a valid user!\nSafeBox Team')
def upload(fp, user): """Upload function, creates a temporary file to which the data of the user file is encrypted to. That temp file is then read by chunks and sent to the CherryPy server Security: - Authentication - File is encrypt with AES - hasher is created for File Integrity Control - Public key is accessed for creating a signature - Private Key is accessed for encrypting the AES key - All relevant information is kept client-side""" (username, session) = user.getInfo() tf = tempfile.NamedTemporaryFile(delete=False) filesize = os.stat(fp).st_size hasher = security.Hasher() pu_key = getPubKey(username) enc, iv, aes = security.getCipher(security.importkey_RSA(pu_key)) with open("PrivateKeys/Private_key_" + str(username), "rb") as f: priv = security.importkey_RSA(f.read()) security.encrypt_AES(open(fp, "rb"), tf, enc, hasher, filesize) h = hasher.get() signature = security.signFile(priv, h) tf.close() f = FileLenIO(tf.name, "rb") list_pu_key = getUsersPubkey(fp.split("/")[-1], username) message = {"filename": fp.split("/")[-1], "iv": iv, "sign": signature.encode("hex")} messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex") # New File if list_pu_key == []: try: request = urllib2.Request("https://localhost:8080/upload", f) request.add_header("Content-Type", "application/octet-stream") request.add_header("username", username) request.add_header("aes", aes) request.add_header("data", messageToSend) request.add_header("Content-Length", os.stat(tf.name).st_size) response = urllib2.urlopen(request) except urllib2.URLError as e: print e.reason print "Currently, you are not a valid user!\nSafeBox Team" # New File Version else: RsaAES = security.decrypt_RSA(priv, aes.decode("hex")) fileList = [] for publickey in list_pu_key: tf2 = tempfile.NamedTemporaryFile(delete=True) security.encrypt_RSA(security.importkey_RSA(publickey.decode("hex")), RsaAES, tf2) fileList += [tf2.read().encode("hex")] try: request = urllib2.Request("https://localhost:8080/uploadExistingFile", f) request.add_header("Content-Type", "application/octet-stream") request.add_header("username", username) request.add_header("aes", json.dumps(fileList)) request.add_header("data", messageToSend) request.add_header("Content-Length", os.stat(tf.name).st_size) response = urllib2.urlopen(request) except urllib2.URLError as e: print e.reason print "Currently, you are not a valid user!\nSafeBox Team" os.remove(tf.name)
def upload(fp, user): """Upload function, creates a temporary file to which the data of the user file is encrypted to. That temp file is then read by chunks and sent to the CherryPy server Security: - Authentication - File is encrypt with AES - hasher is created for File Integrity Control - Public key is accessed for creating a signature - Private Key is accessed for encrypting the AES key - All relevant information is kept client-side""" (username, session) = user.getInfo() tf = tempfile.NamedTemporaryFile(delete=False) filesize = os.stat(fp).st_size hasher = security.Hasher() pu_key = getPubKey(username) enc, iv, aes = security.getCipher(security.importkey_RSA(pu_key)) with open('PrivateKeys/Private_key_' + str(username), 'rb') as f: priv = security.importkey_RSA(f.read()) security.encrypt_AES(open(fp, 'rb'), tf, enc, hasher, filesize) h = hasher.get() signature = security.signFile(priv, h) tf.close() f = FileLenIO(tf.name, 'rb') list_pu_key = getUsersPubkey(fp.split('/')[-1], username) message = { 'filename': fp.split('/')[-1], 'iv': iv, 'sign': signature.encode('hex') } messageToSend = security.encryptS_AES(json.dumps(message), session.decode('hex')).encode('hex') # New File if list_pu_key == []: try: request = urllib2.Request('https://localhost:8080/upload', f) request.add_header('Content-Type', 'application/octet-stream') request.add_header('username', username) request.add_header('aes', aes) request.add_header('data', messageToSend) request.add_header('Content-Length', os.stat(tf.name).st_size) response = urllib2.urlopen(request) except urllib2.URLError as e: print e.reason print 'Currently, you are not a valid user!\nSafeBox Team' # New File Version else: RsaAES = security.decrypt_RSA(priv, aes.decode('hex')) fileList = [] for publickey in list_pu_key: tf2 = tempfile.NamedTemporaryFile(delete=True) security.encrypt_RSA( security.importkey_RSA(publickey.decode('hex')), RsaAES, tf2) fileList += [tf2.read().encode('hex')] try: request = urllib2.Request( 'https://localhost:8080/uploadExistingFile', f) request.add_header('Content-Type', 'application/octet-stream') request.add_header('username', username) request.add_header('aes', json.dumps(fileList)) request.add_header('data', messageToSend) request.add_header('Content-Length', os.stat(tf.name).st_size) response = urllib2.urlopen(request) except urllib2.URLError as e: print e.reason print 'Currently, you are not a valid user!\nSafeBox Team' os.remove(tf.name)