def print_cipher_text_with_colored_n(cipher_texts, possible_xor_bytes, n=1000): for cipher_text in cipher_texts: guess = bytes_xor(cipher_text, possible_xor_bytes).decode("UTF-8") if n < len(guess): print(f'{guess[0:n]}{Fore.GREEN}{(guess[n])}{Style.RESET_ALL}{guess[n+1:]}') else: print(guess)
def find_likely_xor_byte_with_score_alphabet(bytes_str: bytes, percentage: float): result = {} for byte in [bytes([i]) for i in range(2**8)]: decoded_bytes = bytes_xor(bytes_str, cycle(byte)) if score_string(decoded_bytes) > percentage: result[byte] = decoded_bytes return result
def main(): with open( os.path.join(os.getcwd(), '..', '..', '..', 'data', 'set1_6_data'), 'br') as file_handle: encrypted_bytes = base64.b64decode(file_handle.read()) key_size, _, _ = estimate_key_size_for_file(encrypted_bytes, 10, 40) possible_key = break_key_for_key_length(encrypted_bytes, key_size) print(bytes_xor(encrypted_bytes, cycle(possible_key)).decode('utf-8'))
def find_likely_xor_byte_with_alphabet(bytes_str: bytes, percentage: float): result = {} for byte in [bytes([i]) for i in range(2**8)]: decoded_bytes = bytes_xor(bytes_str, cycle(byte)) score = len([ decoded_byte for decoded_byte in decoded_bytes if bytes([decoded_byte]) in ALPHABET_BYTES ]) if score > percentage * len(bytes_str): result[byte] = decoded_bytes return result
def test_set_3_19_20(): test_set = 'set3_20_data' with open(os.path.join(DIR_PATH, '..', 'data', test_set), 'br') as file_handle: data_lines = [ base64.b64decode(data_line) for data_line in file_handle.read().splitlines() ] cipher_texts = encrypt_with_same_nonce(test_set) possible_xor_byte_dicts, possible_xor_bytes = get_initial_likely_bytes( cipher_texts, truncated=True) for cipher_text, answer in zip(cipher_texts, data_lines): assert answer[:len(possible_xor_bytes)] == bytes_xor( cipher_text, possible_xor_bytes)
def test_set_1_5(): my_string = b"Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" encoded_string = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272' \ 'a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f' assert bytes_xor(my_string, cycle(b'ICE')).hex() == encoded_string
def test_set_1_2(): str1 = '1c0111001f010100061a024b53535009181c' str2 = '686974207468652062756c6c277320657965' xor_result = '746865206b696420646f6e277420706c6179' assert xor_result == bytes_xor(bytes.fromhex(str1), bytes.fromhex(str2)).hex()
from cryptopals_challenge_roald.crypto_lib import bytes_xor if __name__ == '__main__': str1 = '1c0111001f010100061a024b53535009181c' str2 = '686974207468652062756c6c277320657965' print(bytes_xor(bytes.fromhex(str1), bytes.fromhex(str2)))