def listContacts(hash): try: FileCredibility.fullStop("contacts.txt") contactFile = open("contacts.txt", "r") except: print("No contacts found. To add a contact write 'add'") return counter = 0 fernet = Fernet(encryption.calculateKey(hash)[0]) line = contactFile.readline()[:-1] if (not line): print("No contacts found. To add a contact write 'add'") while (line): counter = counter + 1 print("\tContact " + str(counter)) print("\tName:\t" + fernet.decrypt(line.encode()).decode()) line = contactFile.readline()[:-1] print("\tEmail:\t" + fernet.decrypt(line.encode()).decode()) line = contactFile.readline()[:-1] if (line): print() contactFile.close() print()
def get_arr_contacts_helper(hash) -> ([str], [str]): masterArrName = [] masterArrEmail = [] try: FileCredibility.fullStop("contacts.txt") contactFile = open("contacts.txt", "r") except: return (masterArrName, masterArrEmail) fernet = Fernet(encryption.calculateKey(hash)[0]) line = contactFile.readline()[:-1] if (not line): return (masterArrName, masterArrEmail) while (line): name = fernet.decrypt(line.encode()).decode() line = contactFile.readline()[:-1] email = fernet.decrypt(line.encode()).decode() masterArrName.append(name) masterArrEmail.append(email) line = contactFile.readline()[:-1] contactFile.close() return (masterArrName, masterArrEmail)
def signFileHelper(fileName, encoding, pri): try: # Load the private key. FileCredibility.fullStop(pri) with open(pri, 'rb') as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend(), ) # Load the contents of the file to be signed. FileCredibility.fullStop(fileName + encoding) with open(fileName + encoding, 'rb') as f: payload = f.read() # Sign the payload file. signature = base64.b64encode( private_key.sign( payload, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH, ), hashes.SHA256(), )) with open(fileName + '.sig', 'wb') as f: f.write(signature) FileCredibility.updateFiles([fileName + '.sig']) except: return False return True
def decrypt_incoming_file( file_name, encoding, one_time_private_key, sal=b'\xdd:\x12\xb3b\xab&\xa6\xaat\xbfM\xc2G\xc7@P\xd3\xba,>\xd5\x91\x06N\xf4\xfe\x0c\xccf\\\xbb' ) -> bool: ca_responce, file = certificate_authority.Authenticate('s.pub') if not ca_responce: raise cryptography.exceptions.InvalidSignature() status = True sym_key = ECDH.compress( ECDH.getShairKey(one_time_private_key, readPublicKey(file))) #sym_key = one_time_private_key url_safe_sym_key = HashPasswords.calcMaster(sym_key, sal, b'', 'sym') FileCredibility.fullStop(file_name + encoding) with open(file_name + encoding, 'rb') as fout: enc_byte_file = fout.read() byte_file = encryption.decrypt_bytes(enc_byte_file, url_safe_sym_key) #base64.decodebytes try: with open(file_name + encoding, 'wb') as fin: fin.write(byte_file) except: status = False FileCredibility.updateFiles([file_name + encoding]) return status
def removeContactHelper(hash, fullName, contactFile): try: FileCredibility.fullStop(contactFile) with open(contactFile, "r") as f: lines = f.readlines() except: print("No contacts found. To add a contact write 'add'") return fernet = Fernet(encryption.calculateKey(hash)[0]) with open(contactFile, "w") as f: bFound = False bMarker = False for line in lines: trueTerm = fernet.decrypt(line[:-1].encode()).decode() if (trueTerm != fullName and bFound == False): f.write(line) else: bMarker = True if (bFound == True): bFound = False else: bFound = True FileCredibility.updateFiles([contactFile]) if (bMarker): print("Successfully removed contact " + fullName + ".\n") else: print("Cannot find \"" + fullName + "\" in contact list.\n") return
def readPublicKey(init_file): FileCredibility.fullStop(init_file) with open(init_file, 'r') as out: content = out.readline().replace('[', '').replace(']', '').split(',') return ec.Point(registry.get_curve(content[0]), int(content[1]), int(content[2]))
def get_public_key(file): FileCredibility.fullStop(file) with open(file, "rb") as key_file: pub_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend() ) return pub_key
def decrypt_symmetric(key_location, input_file_location): masterString = "" fernet_obj = Fernet(get_sym_key(key_location)) FileCredibility.fullStop(input_file_location) for line in open(input_file_location, 'r').readlines(): plaintextLine = fernet_obj.decrypt(line[:-1].encode()).decode() masterString += (str(plaintextLine)) return masterString
def get_private_key(file): FileCredibility.fullStop(file) with open(file, "rb") as key_file: pr_key = serialization.load_pem_private_key(key_file.read(), password=None, backend=default_backend()) return pr_key
def getCondiments(): FileCredibility.fullStop('salt.encrypted') FileCredibility.fullStop('pepper.encrypted') with open('salt.encrypted', 'rb') as out: sal = out.read() with open('pepper.encrypted', 'rb') as out: pep = out.read() return sal, pep
def get_pickle_list(): pickle_list = [] FileCredibility.fullStop(PICKLE_FILE) with open(PICKLE_FILE, 'r') as pickle: pickle_list = pickle.readline() chunks, chunk_size = len(pickle_list), 6 return [ pickle_list[i:i + chunk_size] for i in range(0, chunks, chunk_size) ]
def encrypt_symmetric(encoder, input_file_location, output_file_location): FileCredibility.fullStop(input_file_location) with open(input_file_location, 'rb') as fout: byte_file = fout.read() enc_bytes = encrypt_bytes(byte_file, encoder) with open(output_file_location, "wb") as fin: fin.write(enc_bytes) FileCredibility.updateFiles([output_file_location]) return True
def encrypt_symmetric(encoder, input_file_location, output_file_location): makeClean(output_file_location) fernet_obj = Fernet(calculateKey(encoder)[0]) write = open(output_file_location, "wb") FileCredibility.fullStop(input_file_location) for line in open(input_file_location, 'r'): cypherLine = fernet_obj.encrypt(line.encode()) write.write(cypherLine + "\n".encode()) write.close() FileCredibility.updateFiles([output_file_location]) return True
def addContactHelper(fernet, tempName, tempEmail): FileCredibility.fullStop("contacts.txt") with open("contacts.txt", "a") as f: f.write(fernet.encrypt(tempName.encode()).decode() + "\n") f.write(fernet.encrypt(tempEmail.encode()).decode() + "\n") #f.write("\n") this line makes python think the file ends here, no idea why but yeah #sleep(0.1) FileCredibility.updateFiles(["contacts.txt"]) print("Contact Added.\n") return
def encrypt_file_symmetric(encoder, file_name) -> bool: FileCredibility.fullStop(file_name) success = True encrypt_symmetric(encoder, file_name, 'tmp.txt') try: os.remove(file_name) except: success = False shutil.copyfile('tmp.txt', file_name) os.remove('tmp.txt') return success
def get_sym_key(pri_key_location): priKey = get_private_key(pri_key_location) FileCredibility.fullStop("sym_file.encoded") with open("sym_file.encoded", "rb") as sf: line = sf.read() if not line: return pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) org_bytes = priKey.decrypt(line, pad) return org_bytes
def calcNumContacts(): FileCredibility.fullStop("contacts.txt") with open("contacts.txt", "r") as fContacts: line = fContacts.readline() if (not line): return 0 counter = 0 while (line): counter = counter + 1 line = fContacts.readline() return int(counter / 2)
def debug_pasreq(): check_password_requirements = [] FileCredibility.fullStop('debug.conf') with open('debug.conf', 'r') as debug: debug.readline() debug.readline() check_password_requirements = debug.readline().split('=') if check_password_requirements[0] != 'check_password_requirements': print('Faital error: debug.conf file format wrong') secureDrop.leave() return check_password_requirements[1] == 'True'
def pass_compare_with_pickle(password, sal, pep, unencoded_file, email, return_dict) -> bool: FileCredibility.fullStop('userData.encrypted') with open('userData.encrypted', 'rb') as ud: enc_bytes_file = ud.read() for pickle in get_pickle_list(): try: dec = HashPasswords.calcMaster(password, sal, pep, pickle) bytes_object = encryption.decrypt_bytes(enc_bytes_file, dec) fname, femail = bytes_object.decode().split('\n') if email == femail: return_dict[0] = (True, fname, femail) return except: pass return_dict[0] = (False, '', '')
def login(): email = "" numGuesses = 5 sal, pep = HashPasswords.getCondiments() files = ['pickle.encrypted', 'userData.encrypted', 'userData.psw'] for file in files: FileCredibility.fullStop(file) curHash = HashPasswords.calcPeperHash('pswd'.encode(), sal, pep) print('\n*Email is NOT case-sensitive*', end='') while (numGuesses > 0): email = input("\nEnter Email Address: ") if email.lower() == 'quit': inp = input("You enterd " + email + " ... are you trying to quit the program? (y/n) ") while inp != 'n' and inp != 'y': print(inp + " is not 'y' or 'n'") inp = input("You enterd " + email + " ... are you trying to quit the program? (y/n) ") if inp == 'y': img.bye() leave(False) usrin = encryption.calculateKey( stdiomask.getpass(prompt='Enter Password: '******'userData', email.lower()) if not login_success: numGuesses -= 1 if (numGuesses > 0): print("Incorrect email or password, please try again.") else: print( "Too many incorrect email and password attempts. Exiting SecureDrop." ) img.bye() leave(False) continue curHash = HashPasswords.calcPeperHash(usrin, sal, pep) break return curHash, og_name, og_email
def decrypt_file_symmetric(decoder, file_name, encoding) -> bool: success = True masterString = b'' fernet_obj = Fernet(calculateKey(decoder)[0]) try: lines = b'' FileCredibility.fullStop(file_name + encoding) with open(file_name + encoding, 'rb') as zok: lines = zok.readlines() for line in lines: masterString += fernet_obj.decrypt(line[:-1]) except: success = False with open(file_name + encoding, 'wb') as inpf: inpf.write(masterString) FileCredibility.updateFiles([file_name + encoding]) return success
def unsignFileHelper(fileName, encoding, pub): # Load the public key. FileCredibility.fullStop(pub) with open(pub, 'rb') as f: public_key = serialization.load_pem_public_key(f.read(), default_backend()) # Load the payload contents and the signature. FileCredibility.fullStop(fileName + encoding) with open(fileName + encoding, 'rb') as f: payload_contents = f.read() FileCredibility.fullStop(fileName + '.sig') with open(fileName + '.sig', 'rb') as f: signature = base64.b64decode(f.read()) # Perform the verification. try: public_key.verify( signature, payload_contents, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH, ), hashes.SHA256(), ) except cryptography.exceptions.InvalidSignature: print( f'ERROR: Payload and/or signature files failed verification when varifing {fileName + encoding}' ) return False return True
def dec_file(org_file, key_file) -> str: FileCredibility.fullStop(key_file) return decrypt_symmetric(key_file, org_file)
def sendFile(hash, usr_email): # server info IP = socket.gethostbyname(socket.gethostname()) PORT = 4455 ADDR = (IP, PORT) FORMAT = "utf-8" SIZE = 1024 # see if there are any contacts try: FileCredibility.fullStop("contacts.txt") with open("contacts.txt", "r") as f: contactData = f.readlines() except: print( "No contacts found. Sending a file requires having at least one contact. To add a contact type 'add'\n" ) return # create a TCP socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # connect to the server client.connect(ADDR) except: print("There are no contacts online. Returning to SecureDrop menu.\n") client.close() return # send my info to the contact client.send(usr_email.encode(FORMAT)) try: # get contacts that are online onlineContact = client.recv(SIZE).decode(FORMAT) except: print("\nLost connection to server. Returning to SecureDrop menu.\n") client.close() return # check if online contact is in contact list fernet = Fernet(encryption.calculateKey(hash)[0]) contactFound = False marker = False for line in contactData: if (fernet.decrypt(line[:-1].encode()).decode() == onlineContact) and marker: contactFound = True break else: marker = True # if not in contacts return if (contactFound == False): print( "Someone who is not in your contacts is trying to receive your file. Returning to SecureDrop menu.\n" ) client.close() return print("The following contacts are online:\n * " + onlineContact) contact = input( "\nPlease enter the email of the contact you wish to send a file to>> " ) # check if contact is in contact list fernet = Fernet(encryption.calculateKey(hash)[0]) contactFound = False marker = False for line in contactData: if (fernet.decrypt(line[:-1].encode()).decode() == contact) and marker: contactFound = True break else: marker = True # if not in contacts return if (contactFound == False): print( "Contact not found in contacts list. Returning to SecureDrop menu.\n" ) client.close() return # check if contact entered is actually online if (onlineContact != contact): print("That contact is not online. Returning to SecureDrop menu.\n") client.close() return filename = input("Please enter the name of the file you wish to send>> ") if wishToLeave(filename): client.close() return while not os.path.exists(filename): print("Cannot find file '" + filename + "'.\n") print('You may enter \'quit\' or \'exit\' to leave this prompt.') filename = input( "Please re-enter the name of the file you wish to send>> ") if wishToLeave(filename): client.close() return FileCredibility.updateFiles([filename]) client.send("ready".encode(FORMAT)) print("\nWaiting for contact to accept file transfer...") try: # receive message from server about accepted transfer request msg = client.recv(SIZE).decode(FORMAT) except: print("\n" + contact + " has closed the connection. Returning to SecureDrop menu.\n") client.close() return # if message doesnt actually come from the contact you tried sending to if contact not in msg: print( "The response was not from your contact. Returning to SecureDrop menu.\n" ) client.close() return print(msg) # return to main if contact declines the file if "declined" in msg: print("Returning to SecureDrop menu.\n") client.close() return try: # receive the key file name and data keyFilename = client.recv(SIZE).decode(FORMAT) keyData = client.recv(SIZE).decode(FORMAT) except: print("\n" + contact + " has closed the connection. Returning to SecureDrop menu.\n") client.close() return # save key data with open(keyFilename, "w") as keyFile: keyFile.write(keyData) FileCredibility.updateFiles([keyFilename]) # print("\nReceiver public key file has been received.") # let contact know that key file has been received client.send( "Receiver public key file has been successfully transferred.".encode( FORMAT)) try: # receive signature file name and data sigFilename = client.recv(SIZE).decode(FORMAT) sigData = client.recv(SIZE) except: print("\n" + contact + " has closed the connection. Returning to SecureDrop menu.\n") client.close() return # save signature data with open(sigFilename, "wb") as sigFile: sigFile.write(sigData) FileCredibility.updateFiles([sigFilename]) # system auto authenticates # let client know that the authentication was successful client.send( "Receiver signature file has been transferred and authenticated.". encode(FORMAT)) # predict file size: predicted_size = predictFileSize(filename) client.send(f'size={predicted_size}'.encode(FORMAT)) large_file = False if predicted_size > MAX_RECEIVE_SIZE: large_file = True print( "\nThe file you are encrypting is large. This may take a moment...", end='\r') # generate sender public key file and encrypt the message filename fn = filename.split('.')[0] extension = '.' + filename.split('.')[1] try: sym_key = EncMsg.gen_sender_key_file() except cryptography.exceptions.InvalidSignature: print( '\nr.pub is a forgery! The receiver is not who they say they are!') print("Returning to SecureDrop menu.\n") client.close() return if type(sym_key) == int and sym_key == -1: print("\ncertificate authority declined to sign public key file") print("Returning to SecureDrop menu.\n") client.close() return if EncMsg.gen_send_file(sym_key, fn, extension): if large_file: print( "The file you are encrypting is large. This may take a moment... Success!" ) else: print("Failed to encrypt the file. ERROR_26: file too large") # send the sender public key filename client.send("s.pub".encode(FORMAT)) # get key data FileCredibility.fullStop("s.pub") with open("s.pub", "rb") as sender_public_key_file: sender_public_key_data = sender_public_key_file.read() # send the sender public key data client.send(sender_public_key_data) try: # receive message about successfull public key file transfer msg = client.recv(SIZE).decode(FORMAT) # print(msg) except: print("\n" + contact + " has closed the connection. Returning to SecureDrop menu.\n") client.close() return # send the sender signature filename client.send("s.sig".encode(FORMAT)) # get signature file data FileCredibility.fullStop("s.sig") with open("s.sig", "rb") as sender_sig_file: sender_sig_data = sender_sig_file.read() # send sig file data client.send(sender_sig_data) try: # receive message about successful transfer of sig file msg = client.recv(SIZE).decode(FORMAT) # print(msg) except: print("\n" + contact + " has closed the connection. Returning to SecureDrop menu.\n") client.close() return # send enc-message filename to server client.send(filename.encode(FORMAT)) # send enc-message file size to server filesize = getFileSize(filename.split('.')[0] + '.zok') client.send(f'size={filesize}'.encode(FORMAT)) # get encrypted message data fenc = filename.split(".")[0] + ".zok" FileCredibility.fullStop(fenc) file = open(fenc, "rb") data = file.read() file.close() try: decision = client.recv(SIZE).decode(FORMAT) except: print("\n" + contact + " has closed the connection. Returning to SecureDrop menu.\n") client.close() return if decision == 'n': print("\n" + contact + " has declined the large file. Returning to SecureDrop menu.\n") client.close() return print(f'\n{filename} sending...', end='\r') # send encrypted message data client.sendall(data) # receive message from server about successful file transfer try: msg = client.recv(SIZE).decode(FORMAT) if ' has been successfully transferred.' in msg: print(f'{filename} has been successfully transferred!\n') else: print("\n" + msg + "\n") except: print("\n" + contact + " has closed the connection. Returning to SecureDrop menu.\n") client.close() return # end connection from server client.close() return
def readPsw(unencoded_file): FileCredibility.fullStop(unencoded_file + '.psw') with open(unencoded_file + '.psw', 'rb') as f: obj = f.read() return obj