def _more_init(self): """ Called as first function in run() """ # Closing the lockfile descriptor. # # The multiprocessing library behaves differently on Windows and Unix: # - on Windows it spawns a Python interpreter in a brand new process, # which doesn't share any resource with the father process; # - on Unix it forks. The child process inherits by default all # file descriptors from the father, that is, open files, sockets, # etc. # We want subprocesses not to inherit the lockfile descriptor in # order to avoid stale locks (see module: filerockclient.application). # It isn't possible to avoid Unix subprocesses to inherit descriptors, # so the only safe option is to explicitly close the lockfile in the # child. However, it must not be done on Windows, since multiprocessing # very likely uses the very same file descriptor for different # resources. # The developers of multiprocessing seem to be working on the fd # inheritance problem right in these days, see: # http://bugs.python.org/issue8713 if not sys.platform.startswith('win'): os.close(self.lockfile_fd) # self.warebox = Warebox(self.cfg) self.encrypter = Encrypter(self.warebox_path) self.decrypter = Decrypter(self.warebox_path)
def client_b_thread(conn, ip, port): global client_a_enc_mode, encrypted_message_pickle conn.sendall(bytes(client_a_enc_mode.encode('utf8'))) while client_a_enc_mode == '': conn.sendall(bytes(client_a_enc_mode.encode('utf8'))) conn.sendall(bytes(client_a_enc_mode.encode('utf8'))) conn.sendall(bytes(client_a_enc_mode.encode('utf8'))) if client_a_enc_mode == 'cbc': # if client a uses cbc, client b will use cfb, and vice versa encrypted_key = Encryptor.simulate_aes_cfb_encryption(secret_key2, secret_key3, iv_k3)[0] encrypted_iv_k2 = Encryptor.simulate_aes_cfb_encryption(iv_k2, secret_key3, iv_k3)[0] else: encrypted_key = Encryptor.simulate_aes_cbc_encryption(secret_key2, secret_key3, iv_k3)[0] encrypted_iv_k2 = Encryptor.simulate_aes_cbc_encryption(iv_k2, secret_key3, iv_k3)[0] response = pickle.dumps([client_a_enc_mode, encrypted_key, encrypted_iv_k2]) conn.sendall(response) # receive encrypted key as confirmation message data = conn.recv(2048) encrypted_key_to_confirm = pickle.loads(data) if client_a_enc_mode == 'cbc': key_to_confirm = Decrypter.simulate_aes_cfb_decryption([encrypted_key_to_confirm], secret_key3, iv_k3) else: key_to_confirm = Decrypter.simulate_aes_cbc_decryption([encrypted_key_to_confirm], secret_key3, iv_k3) print('[Client B] send confirmation key: ', key_to_confirm) if key_to_confirm == secret_key2: print('Key is valid!') # send confirmation for secure communication conn.sendall('[SERVER] Secure connection established!'.encode('utf')) else: print('Key is invalid!') conn.sendall('[SERVER] Secure connection cannot be established!'.encode('utf')) # send encrypted contend to client b while encrypted_message_pickle == '': pass conn.sendall(encrypted_message_pickle) print('[SERVER] Encrypted data send successfully!')
def test_calculate_fibonacci(self) -> None: self.assertEqual(Decrypter.calculate_fibonacci(0), 0) self.assertEqual(Decrypter.calculate_fibonacci(1), 1) self.assertEqual(Decrypter.calculate_fibonacci(5), 5) self.assertEqual(Decrypter.calculate_fibonacci(7), 13) self.assertEqual(Decrypter.calculate_fibonacci(9), 34) self.assertEqual(Decrypter.calculate_fibonacci(50), 12586269025)
def find_and_print_cypher_and_decrypted_lines(corpus_path, encrypted_path, print_cypher, print_decrypted, verbose, output_directory): found_cypher, cypher = CypherFinder(corpus_path, verbose).get_cypher(encrypted_path) if found_cypher: decrypter, decrypted_file, cypher_file = Decrypter(cypher), None, None if output_directory != '': decrypted_file = open('{}/decrypted.txt'.format(output_directory), 'w') cypher_file = open('{}/cypher.txt'.format(output_directory), 'w') with open(encrypted_path) as encrypted_file: for line in encrypted_file: line = line.replace('\n', '') if line != '': output_line = decrypter.decrypt(line) if print_decrypted or verbose: print(output_line) if decrypted_file != None: decrypted_file.write('{}\n'.format(output_line)) if decrypted_file != None: decrypted_file.close() for _, v in enumerate(sorted(cypher)): output_line = '{} -> {}'.format(v, cypher[v]) if print_cypher or verbose: print(output_line) if cypher_file != None: cypher_file.write('{}\n'.format(output_line)) if cypher_file != None: cypher_file.close() else: print('Could not find cypher')
def client_a_thread(conn, ip, port): global client_a_enc_mode, encrypted_message_pickle encryption_mode = conn.recv(128).decode('utf8') if encryption_mode.lower() == 'cbc': client_a_enc_mode = 'cbc' encrypted_key = Encryptor.simulate_aes_cbc_encryption(secret_key1, secret_key3, iv_k3)[0] encrypted_iv_k1 = Encryptor.simulate_aes_cbc_encryption(iv_k1, secret_key3, iv_k3)[0] else: client_a_enc_mode = 'cfb' encrypted_key = Encryptor.simulate_aes_cfb_encryption(secret_key1, secret_key3, iv_k3)[0] encrypted_iv_k1 = Encryptor.simulate_aes_cfb_encryption(iv_k1, secret_key3, iv_k3)[0] response = pickle.dumps([encryption_mode, encrypted_key, encrypted_iv_k1]) conn.sendall(response) # receive encrypted key as confirmation message data = conn.recv(128) encrypted_key_to_confirm = pickle.loads(data) if encryption_mode == 'cbc': key_to_confirm = Decrypter.simulate_aes_cbc_decryption([encrypted_key_to_confirm], secret_key3, iv_k3) else: key_to_confirm = Decrypter.simulate_aes_cfb_decryption([encrypted_key_to_confirm], secret_key3, iv_k3) print('[Client A] send confirmation key: ', key_to_confirm) if key_to_confirm == secret_key1: print('Key is valid!') # send confirmation for secure communication conn.sendall('[SERVER] Secure connection established!'.encode('utf')) else: print('Key is invalid!') conn.sendall('[SERVER] Secure connection cannot be established!'.encode('utf')) response = conn.recv(20480000) decoded_response = pickle.loads(response) if encryption_mode == 'cbc': decrypted_counter = Decrypter.simulate_aes_cbc_decryption(decoded_response[0], secret_key1, iv_k1) decrypted_file_content = Decrypter.simulate_aes_cbc_decryption(decoded_response[1], secret_key1, iv_k1) else: decrypted_counter = Decrypter.simulate_aes_cfb_decryption(decoded_response[0], secret_key1, iv_k1) decrypted_file_content = Decrypter.simulate_aes_cfb_decryption(decoded_response[1], secret_key1, iv_k1) print('[SERVER] Decrypted file content:') print(decrypted_file_content) # encrypting data and sending it to client b if encryption_mode == 'cbc': encrypted_counter = Encryptor.simulate_aes_cfb_encryption(decrypted_counter, secret_key2, iv_k2)[0] encrypted_content = Encryptor.simulate_aes_cfb_encryption(decrypted_file_content, secret_key2, iv_k2) else: encrypted_counter = Encryptor.simulate_aes_cbc_encryption(decrypted_counter, secret_key2, iv_k2)[0] encrypted_content = Encryptor.simulate_aes_cbc_encryption(decrypted_file_content, secret_key2, iv_k2) encrypted_message_pickle = pickle.dumps([encrypted_counter, encrypted_content])
def process_video(self, video_metadata, mkv_filepath, root_url, progress_bar_value, callback_func): """ Download video and decrypt, join, encode to mkv :return: """ ttid = video_metadata['ttid'] number_of_tracks = int(video_metadata['tapNToggle']) duration = int(video_metadata['actualDuration']) encryption_keys = dict() self.logger.info("[{}]: Starting download for {}".format( ttid, mkv_filepath)) # download media files for this video. m3u8_content = self._download_m3u8(root_url, ttid) if m3u8_content: summary, tracks_info = M3u8Parser( m3u8_content, num_tracks=number_of_tracks).parse() download_dir = os.path.join(self.temp_downloads_dir, str(ttid)) os.makedirs(download_dir, exist_ok=True) temp_files_to_delete = set() ts_files = list() items_processed = 0 for track_index, track_info in enumerate(tracks_info): streams_to_join = list() for item in track_info: # download encrypted stream.. enc_stream_filepath = '{}/{}'.format( download_dir, item['file_number']) temp_files_to_delete.add(enc_stream_filepath) download_flag = False while not download_flag: try: with open(enc_stream_filepath, 'wb') as fh: content = requests.get(item['url']).content fh.write(content) download_flag = True except TimeoutError: self.logger.warning( "[{}]: Timeout error. retrying download for {}..." .format(ttid, item['url'])) time.sleep(self.conf.get('retry_wait')) # decrypt files if encrypted. if item.get('encryption_method') == "NONE": streams_to_join.append(enc_stream_filepath) else: if not encryption_keys.get(item['encryption_key_id']): key = self.session.get( item['encryption_key_url']).content[2:] key = key[::-1] # reverse the bytes. encryption_keys[item['encryption_key_id']] = key encryption_key = encryption_keys[ item['encryption_key_id']] decrypted_stream_filepath = Decrypter.decrypt( encryption_key, enc_stream_filepath, download_dir) streams_to_join.append(decrypted_stream_filepath) temp_files_to_delete.add(decrypted_stream_filepath) # update progress bar items_processed += 1 items_processed_percent = items_processed * 100 // summary.get( 'media_files') callback_func(items_processed_percent) # progress_bar_value.set(items_processed * 100 // summary.get('media_files')) # All stream files for this track are decrypted, join them. self.logger.info( "[{}]: joining streams for track {} ..".format( ttid, track_index)) ts_file = Encoder.join(streams_to_join, download_dir, track_index) ts_files.append(ts_file) temp_files_to_delete.add(ts_file) # Encode all ts files into a single output mkv. os.makedirs(os.path.dirname(mkv_filepath), exist_ok=True) success = Encoder.encode_mkv(ttid, ts_files, mkv_filepath, duration, self.conf.get('debug')) if success: self.logger.info("[{}]: Processed {}\n---".format( ttid, mkv_filepath)) # delete temp files. if not self.conf.get('debug'): Utils.delete_files(list(temp_files_to_delete)) os.rmdir(download_dir)
if encryption_mode == 'cbc': print('Your encryption mode is cfb!') else: print('Your encryption mode is cbc!') # receive the encryption mode used, encrypted key and encrypted iv response = soc.recv(2048) encrypted_data = pickle.loads(response) encryption_mode = encrypted_data[0] encrypted_key2 = encrypted_data[1] encrypted_iv_k2 = encrypted_data[2] if encryption_mode == 'cfb': decrypted_key2 = Decrypter.simulate_aes_cbc_decryption([encrypted_key2], secret_key3, iv_k3) decrypted_iv_k2 = Decrypter.simulate_aes_cbc_decryption([encrypted_iv_k2], secret_key3, iv_k3) else: decrypted_key2 = Decrypter.simulate_aes_cfb_decryption([encrypted_key2], secret_key3, iv_k3) decrypted_iv_k2 = Decrypter.simulate_aes_cfb_decryption([encrypted_iv_k2], secret_key3, iv_k3) decrypted_iv_k2 = bytes(decrypted_iv_k2.encode('utf8')) # sending the encrypted key back for confirmation if encryption_mode == 'cfb': encrypted_key_to_confirm = Encryptor.simulate_aes_cbc_encryption( decrypted_key2, secret_key3, iv_k3)[0] else:
charCounter.add_char(char) char = file.read(1) # print("char count") # print(charCounter.get_char_counter()) #init huffman tree huffmanTree = build_tree(charCounter.get_char_counter()) # huffmanTree.preorder_print(huffmanTree.get_root()) #get presentation from tree presentation = {} huffmanTree.get_tree_nodes(huffmanTree.get_root(), presentation) print("presentation") print(presentation) # #init encryp encrypter = Encrypter(presentation) print(encrypter.get_decrypt_char()) doEncryption = raw_input("encrypt file y/n\n") if doEncryption == "y": encrypter.encrypt_file(file) # #init decrypter decrypter = Decrypter(encrypter.get_decrypt_char()) doDecryption = raw_input("decrypt file y/n\n") if doDecryption == "y": decrypter.decrypt_file(file) #check if user want to quit or no quit = raw_input("exit y/n\n") if quit == "y": file.close() break print("Thank you for using huffman tree") exit(0)
encryption_mode = input('Enter encryption mode: `CBC` or `CFB`: ') while encryption_mode.lower() not in ['cbc', 'cfb']: encryption_mode = input('Enter encryption mode: `CBC` or `CFB`: ') soc.sendall(bytes(encryption_mode.encode('utf8'))) # receive the encryption mode used, encrypted key and encrypted iv response = soc.recv(1024) encrypted_data = pickle.loads(response) # client a already knows encryption mode, doesn't need to extract it encrypted_key = encrypted_data[1] encrypted_iv_k1 = encrypted_data[2] if encryption_mode == 'cbc': decrypted_key1 = Decrypter.simulate_aes_cbc_decryption([encrypted_key], secret_key3, iv_k3) decrypted_iv_k1 = Decrypter.simulate_aes_cbc_decryption([encrypted_iv_k1], secret_key3, iv_k3) else: decrypted_key1 = Decrypter.simulate_aes_cfb_decryption([encrypted_key], secret_key3, iv_k3) decrypted_iv_k1 = Decrypter.simulate_aes_cfb_decryption([encrypted_iv_k1], secret_key3, iv_k3) # sending the encrypted key back for confirmation if encryption_mode == 'cbc': encrypted_key_to_confirm = Encryptor.simulate_aes_cbc_encryption( decrypted_key1, secret_key3, iv_k3)[0] else: encrypted_key_to_confirm = Encryptor.simulate_aes_cfb_encryption( decrypted_key1, secret_key3, iv_k3)[0]
def setUp(self): # Arrange self._uut = Decrypter()
class DecrypterTest(unittest.TestCase): def setUp(self): # Arrange self._uut = Decrypter() # region ComputeHammingDistance def test_ComputeHammingDistance_ValidInput_DistanceIsCorrectValue(self): # Arrange test_string1 = b'this is a test' test_string2 = b'wokka wokka!!!' distance = 0 # Act distance = self._uut.compute_hamming_distance(test_string1, test_string2) # Assert self.assertEqual(distance, 37) def test_ComputeHammingDistance_LengthIsNotEqual_DistanceIsMinusOne(self): # Arrange test_string1 = b'this is a test' test_string2 = b'wokka wokka!!!wokka wokka!!!' distance = 0 # Act distance = self._uut.compute_hamming_distance(test_string1, test_string2) # Assert self.assertEqual(distance, -1) # endregion ComputeHammingDistance # region SingleCharBruteForce def test_SingleByteXOr_ValidInput_XOrOutputIsCorrect(self): # Arrange # test_data found with help from https://www.dcode.fr/xor-cipher test_data = b',=+,' test_key = b'X' expected_xor_output = b'test' result = b'' # Act result = self._uut.singlebyte_xor(test_data, test_key) # Assert self.assertEqual(result, expected_xor_output) def test_RateText_ValidText_RatingIsCorrect(self): # Arrange test_text = b'this text is awesome, that\'s what she said' test_text2 = 'THIS TEXT IS AWESOME, ThAT\'S WhAt sHe sAId' expected_rating = 4.0 result = 0 # Act result = self._uut.rate_text(test_text) result2 = self._uut.rate_text(test_text2) # Assert self.assertEqual(result, expected_rating) self.assertEqual(result2, expected_rating) def test_RateText_AllCommonWords_RatingIsCorrect(self): # Arrange test_text = b'THISandTHAThaveTHE' expected_rating = 4.71 result = 0 # Act result = self._uut.rate_text(test_text) # Assert self.assertEqual(result, expected_rating) # region EqualLengthXOr def test_EqualLengthInputXor_ValidInput_XOrOutputIsCorrect(self): # Arrange test_data1 = b'1c0111001f010100061a024b53535009181c' test_data2 = b'686974207468652062756c6c277320657965' expected_xor_output = b'746865206b696420646f6e277420706c6179' result = b'' # Act result = self._uut.equal_length_inputs_xor(test_data1, test_data2) # Assert self.assertEqual(result, expected_xor_output) # endregion EqualLengthXOr # region AES_in_ECB_mode def test_easInECBmode_Decrypt_CorrectPlainText(self): from binascii import unhexlify, hexlify # Arrange # test data from https://www.devglan.com/online-tools/aes-encryption-decryption # encrypt: 'testTESTtestTEST' test_data1 = bytes.fromhex( 'D5119B1375DDCFF464479495F34830D660FA36707E45F499DBA0F25B922301A5') test_key = b'YELLOW SUBMARINE' expected_result = b'testTESTtestTEST' result = b'' # Act result = self._uut.decrypt_aes_128b_ecb(test_data1, test_key) # Assert self.assertEqual(result, expected_result)
def setUpClass(cls) -> None: cls.__decrypter = Decrypter()
def test_subtract_min_max(self) -> None: self.assertEqual( Decrypter.subtract_min_max(Decrypter.calculate_fibonacci(7)), 2) self.assertEqual( Decrypter.subtract_min_max(Decrypter.calculate_fibonacci(9)), 1)
def decrypt_all() -> None: """ This function uses the list of possible paths for drivers connected to the machine from the "util" file to decrypt them (only available on Windows). """ for drive in drivers: try: chdir(drive + '/') decrypter.decrypt_directory(drive) except FileNotFoundError: continue except PermissionError: continue decrypter = Decrypter() desktop = expanduser('~/Desktop') documents = expanduser('~/Documents') downloads = expanduser('~/Downloads') onedrive = expanduser('~/OneDrive') # Removing the created registry exe = decrypter.delete_registry( r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 'Rain') decrypter.delete_registry(r'', 'WINDAT32_HOURS') # These lines use system commands to show the ransomware file and remove it # (placed in C:\Users\Public\filename.exe). try: command = f'attrib -s -h {exe}'