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 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 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 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 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 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_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 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_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 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 write_new_keys_to_file(file_one, file_two): if pub_and_pri_not_exist(): privateKey = gen_private_key() with open(file_one, "w") as private_key_file: # "example-rsa.pem" private_key_file.write(encrypt_private_key(privateKey).decode()) with open(file_two, "w") as public_key_file: # "example-rsa.pub" public_key_file.write(gen_public_key(privateKey).decode()) FileCredibility.updateFiles([file_one, file_two])
def generate_pickle_list(): if file_path.exists(PICKLE_FILE): return with open(PICKLE_FILE, 'w') as f_pickle: for i in range(10): f_pickle.write(''.join(choices(uppercase + lowercase + digits, k=6))) FileCredibility.updateFiles([PICKLE_FILE]) time.sleep(0.1)
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 gen_receiver_key_file(): PriPubPair = new_Pri_Pub(99999999) pri_key = PriPubPair[0] pub_key = PriPubPair[1] with open('r.pub', 'w') as write: write.write(formatKey(pub_key)) FileCredibility.updateFiles(['r.pub']) responce, _ = certificate_authority.requestSignature('r.pub') if not responce: return -1 return pri_key
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 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 save_sym_key(sym_key, pub_key_location): with open("sym_file.encoded", 'wb') as write: pubKey = get_public_key(pub_key_location) pad = padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) encrypted_bytes = pubKey.encrypt(sym_key, pad) write.write(encrypted_bytes) FileCredibility.updateFiles(["sym_file.encoded"])
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 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 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 registerUser(): tempFile = input("Enter Full Name: ") + '\n' tempFile += input("Enter Email Address: ").lower() numTries = 3 while (numTries > 0): print( "Password must:\n\tBE: \t8 to 25 chars\n\tHAVE:\tAt least one uppercase letter\n\tHAVE:\tAt least one lowercase letter\n\tHAVE:\tAt least one diget" ) pswd1, len_and_contains_up_low_dig = encryption.calculateKey( stdiomask.getpass(prompt='Enter Password: '******'That password is missing or failing one or more of the requirements...\n' ) continue if pswd1 != encryption.calculateKey( stdiomask.getpass(prompt='Re-Enter Password: '******'userData.encrypted' with open(user_file, 'wb') as uf: uf.write(bytes_object) FileCredibility.updateFiles([user_file]) print("User registered.\n")
def gen_sender_key_file(): ca_responce, file = certificate_authority.requestSignature('r.pub') if not ca_responce: raise cryptography.exceptions.InvalidSignature() external_public_key = readPublicKey(file) pri_key = ECDH.getPri(external_public_key.curve) pub_key = ECDH.getPub(pri_key, external_public_key.curve) with open('s.pub', 'w') as write: write.write(formatKey(pub_key)) FileCredibility.updateFiles(['s.pub']) responce, _ = certificate_authority.requestSignature('s.pub') if not responce: return -1 return ECDH.compress(pri_key * external_public_key)
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 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 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 reset(printable=True): files = os.listdir('./') for file in files: if file.endswith(".zok") or file.endswith(".encrypted"): os.remove(file) for file in FILES_TO_REMOVE: try: os.remove(file) except: pass FileCredibility.gen_dependencies_key() if not os.path.exists('dependencies.enc'): with open('dependencies.enc','w'): pass with open('dependencies.enc',"r+") as file: file.truncate(0) FileCredibility.updateFiles(CERTIFICATE_FILES + PYTHON_FILES + SELF_IMG_FILES) if printable: print("reset")
def init(): if unpack.ispacked(): unpack.unpack() print('') FileCredibility.VerifyFiles() img.out() # print SecureDrop logo if getNumUsers() == 0: print("No users are registered with this client.") c = input("Do you want to register a new user (y/n)? ") while 'n' != c != 'y' and 'N' != c != 'Y': c = input("Do you want to register a new user (y/n)? ") if (c == 'n'): img.bye() leave(False) else: registerUser()