def encryptFile( user: User ): g.cls() print(" #### ENCRIPTAR ARCHIVO ####") # OBTENCION DEL ARCHIVO A ENCRIPTAR root = Tk() root.iconbitmap(r'logoUcu.ico') root.wm_withdraw() fileDir = askopenfilename(title="Elegir Archivo", filetypes=([("Binarios", "*.bin")])) root.destroy() if fileDir == "": return print(" > Encriptando: " +fileDir) fileName = fileDir[fileDir.rfind("/")+1:] # ENCRIPTAR EL ARCHIVO CON UNA CLAVE ALEATORIA fileKey = c.getRandomAESKey() c.encryptFile( fileDir, fileKey ) # GENERAR EL ARCHIVO CON LA CLAVE SIMETRICA ENCRIPTADA CON MI PUBLICA ownPublicKey = u.getUserListLine( user.index)[2] encryptedKey = c.encryptKey( fileKey, ownPublicKey ) print(" > Archivo encriptado exitosamente!") # GUARDAR UNA COPIA DEL ARCHIVO CIFRADA CON LA CLAVE PUBLICA DEL AUTOR with open(getEncryptedKeyAddr(user, fileName), 'wb') as outFile: outFile.write(encryptedKey) if encryptKey4Share(user,fileKey,fileName): popUp(" > Transferencia realizada exitosamente!") return
def selectAddressees(user: User): # MOSTRAR LISTA DE USUARIOS PARA DARLES LA CLAVE print(" Seleccione Usuarios con los que compartir el archivo") print(" Para seleccionar varios usuarios, ingresar una lista separada por espacios") i = 1 validIndexes = [] possibleUsers = [] # Mostrar la Lista de Usuarios while True: [uName, uRole, uPub, uLast] = u.getUserListLine(i) if i != user.index: print(" " + str(i) + ". " + uName + ": " + uRole) possibleUsers.append(User(userName=uName, role=uRole, public=uPub, index=i)) validIndexes.append(i) i += 1 if uLast: break people = i #Mostrar la lista de roles print( " O seleccione un rol para compartirlo con todos sus miembros" ) roles = u.getRolesFromList() for x in roles: print(" "+str(i) + ". " + x) validIndexes.append(i) i += 1 selection = input() # Obtener los indices validos ingresados tempDest = [int(x) for x in selection.split() if x.isdigit()] # Obtiene los numeros de lo que se haya ingresado if not tempDest: # si no hay numeros, se va return tempIndexes = [] dest = [] [tempIndexes.append(x) for x in tempDest if x in validIndexes] for x in tempIndexes: if x > people: #se trata de un indice correspondiente a un rol others = u.getOtherUsersPerRole( user, roles[x-people] ) [dest.append(y) for y in others] [dest.append(possibleUsers[x]) for x in range(len(possibleUsers)) if possibleUsers[x].index in tempIndexes and possibleUsers[x] not in dest ] print(" El archivo se compartirá con:") [print(" " + dest[x].userName) for x in range(len(dest))] print(" Para compartir un archivo reingrese su contraseña.") while True: inPsw = getpass.getpass(prompt=" Contraseña: ") if inPsw == "": retriesLogic(True) popUp(" > Abortado!") return [] valid = psw_validate(user.userName, inPsw)[0] if valid: retriesLogic(True) break elif not retriesLogic(False): popUp(" > No es posible compartir el archivo!") return [] return dest
def shareFile(user: User): print(" #### COMPARTIR ARCHIVO ####") # ELEGIR ARCHIVO A COMPARTIR oldWd = os.getcwd() # Respaldar el working directory para reestablecerlo luego os.chdir(u.getuserArchivesAddr( user)) # se cambia el working directory para trabajar mas facil con los archivos del usuario # Obtener el nombre de cada archivo del cual tengo la clave print(" Seleccione el archivo a compartir") files = [] i = 1 for file in glob.glob("*.bin"): print(str(i) + ". " + file[len( user.userName) + 1:-4]) # No mostrar ni el prefijo con el nombre de usuario ni la extension files.append(file) i += 1 os.chdir(oldWd) file2ShareIndex = input() if not file2ShareIndex.isnumeric(): return file2ShareIndex = int(file2ShareIndex) -1 # DESENCRIPTAR LA CLAVE SIMETRICA DE ESE ARCHIVO, USANDO LA CLAVE PRIVADA DEL USUARIO decryptedKey = decryptKeyFromAddr(user, u.getuserArchivesAddr(user) + files[file2ShareIndex]) # ELEGI DESTINATARIOS Y ENCRIPTARLES UNA COPIA DE LA CLAVE CON SU CLAVE PUBLICA if encryptKey4Share(user, decryptedKey, files[file2ShareIndex][len(user.userName)+1:]): popUp("> Transferencia realizada exitosamente!") return
def psw_validate(userName: str, inPsw: str) -> bool: with open(userList, 'rb') as inFile: sFile = inFile.read() inPsw = inPsw.encode(encoding) userStart = sFile.find(userName.encode(encoding)) # OBTENER EL SALT saltStart = sFile.find(prefixSalt, userStart) + len(prefixSalt) saltEnd = sFile.find(userListOrder[userListOrder.index(prefixSalt) + 1], saltStart) salt = sFile[saltStart:saltEnd] # SALTEAR Y HASHEAR LA PSW INGRESADA hashedPsw = c.hashPsw(inPsw, salt) # OBTENER LA PSW storedPswStart = sFile.find(prefixPassWord, userStart) + len(prefixPassWord) storedPswEnd = sFile.find( userListOrder[userListOrder.index(prefixPassWord) + 1], storedPswStart) storedPsw = sFile[storedPswStart:storedPswEnd] # COMPARAR PSWs if hashedPsw == storedPsw: popUp("> Contraseña correcta!") retriesLogic(True) return True, salt else: print("> Contraseña incorrecta!") return False, None
def addUser(firstUser: bool = False): print(" #### NUEVO USUARIO ####") role = input(" Ingrese el Rol: ") while True: invalid = False userName = input(" Ingrese el nombre de usuario: ") # chequear que el nombre de usuario no exista ya! if firstUser: break i = 1 while True: [uName, *_, uLast] = getUserListLine(i) i += 1 if uName == userName: invalid = True popUp("> El nombre de usuario ya existe!") break if uLast: break if not invalid: break # Ingreso de Contraseña while True: password = getpass.getpass(" Ingrese contraseña: ") checkMsg = pswRequisites(password) if checkMsg == True: password2 = getpass.getpass(" Reingrese contraseña: ") if password != password2: print(" > Contraseñas no coinciden!") continue break else: print(checkMsg) print(" GENERANDO USUARIO...") generateUser(userName, password, role)
def decryptFile(user: User): g.cls() print(" #### DESENCRIPTAR ARCHIVO ####") # OBTENCION DEL ARCHIVO A DESENCRIPTAR root = Tk() root.iconbitmap(r'logoUcu.ico') root.wm_withdraw() fileDir = askopenfilename(title="Elegir Archivo", filetypes=([("Binarios", "*.bin")])) root.destroy() if fileDir == "": return print(" > Desencriptando: " +fileDir) fileName = fileDir[fileDir.rfind("/")+1:] oldWd = os.getcwd() # Respaldar el working directory para reestablecerlo luego os.chdir(u.getuserArchivesAddr(user)) # se cambia el working directory para trabajar mas facil con los archivos del usuario encryptedKeyFileName = False for file in glob.glob("*.bin"): # Obtener el nombre de cada archivo del cual tengo la clave if file.find(fileName) == len(user.userName)+1: #los nombres de las claves encriptadas son: <nombre Usuario>_<nombre del archivo>.bin encryptedKeyFileName = file break os.chdir(oldWd) # Se devuelve el WD al oroginal if encryptedKeyFileName is False: popUp(" > NO ES POSIBLE DESENCRIPTAR EL ARCHIVO" ) return # DESENCRIPTAR LA CLAVE decryptedKey = decryptKeyFromAddr(user,u.getuserArchivesAddr(user) + encryptedKeyFileName) # DESENCRIPTAR EL ARCHIVO c.decryptFile(fileDir,decryptedKey) popUp(" > Archivo desencriptado exitosamente") os.chdir(oldWd) # Se devuelve el WD al oroginal return
def authorization() -> (User, bool): print(" #### ACCESO AL SISTEMA ####") with open(userList, 'rb') as inFile: sFile = inFile.read() while True: # Obtener Nombre de Usuario userName = input(" Nombre de Usuario: ") if userName == "": retriesLogic(True) popUp("> Cerrando!") return None, False userStart = sFile.find(userName.encode(encoding)) incomplete = sFile[userStart:sFile.find( userListOrder[userListOrder.index(prefixUserName) + 1], userStart)].decode(encoding) != userName # Si no hubo match o el match se dio en un lugar que no es un nombre El nombre ingresado es exactamente to do el nombre que hay guardado if userStart < 0 or sFile[userStart - len(prefixUserName): userStart] != prefixUserName or incomplete: popUp("> Usuario no existe!") continue # Obtener contraseña y chequearla while retriesLogic(False): inPsw = getpass.getpass(prompt=" Contraseña: ") if inPsw == "": retriesLogic(True) popUp("> Cerrando!") return None, False valid, salt = psw_validate(userName, inPsw) if valid: # OBTENER EL INDICE DEL USUARIO indexStart = sFile.find(prefixIndex, userStart) + len(prefixIndex) indexEnd = sFile.find( userListOrder[userListOrder.index(prefixIndex) + 1], indexStart) index = int.from_bytes(sFile[indexStart:indexEnd], 'big') # CREAR EL USUARIO PARA DEVOLVER user = User(userName=userName, AESkey=c.deriveAESkey(str(inPsw), str(salt)), index=index) return user, True print("ACCESO DENEGADO") return None, False
import userInfo as u import menu as m import gral as g from gral import popUp # COMMIT: VERSION FUNCIONAL print(" #### INICIANDO SISTEMA ####") u.generateTable() g.cls() while True: # CONTROL DE ACCESO (user, valid) = u.authorization() if not valid: quit() g.cls() # CARGAR LA INFORMACION DEL USUARIO QUE ACABA DE INGRESAR user = u.getInfoFromUserFile(user) if user is None: popUp(" > NO SE PUDO CARGAR LA INFO DEL USUARIO") quit() # MENU PPAL while True: if m.showMenu(user): break g.cls() popUp(" CHAU :D ")