def hamming_distance(x, y): assert len(x) == len(y) sum = 0 for b in xor(x, y): sum += bin(ord(b)).count('1') return sum
def decrypt(k,c): """ xors the ciphertext bytestring with key k and returns as bytestring param k: key param c: ciphertext bytes return a string of bytes """ decrypted = '' for byte in c: decrypted += xor(byte, k) return decrypted
def hex_string_xor(hex1string, hex2string): """ A complete function for reading in two hex strings and outputting a string of the xor of the two inputs :param hex1_string: a string of ASCII encoded hex characters :param hex2_string: a string of ASCII encoded hex characters :return: a string of ASCII encoded hex characters """ assert type(hex1string) == str assert type(hex2string) == str hex1bytes = hex_to_bytestr(hex1string) hex2bytes = hex_to_bytestr(hex2string) outputbytes = xor(hex1bytes, hex2bytes) print(outputbytes) outputstring = bytestr_to_hex(outputbytes) return outputstring
if __name__ == "__main__": input1='1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' Bytes = converters.hex_to_bytestr(input1) print('Bytes:', Bytes) potential_keys=[] # if a repeated character exists, the potential keys are reduced to keys which # will decrypt to a repeated character found in the English language, namely s,e,t,m,o if len(repeated(Bytes))>0: for item in repeated(Bytes): for k in ['s', 'e', 't', 'l', 'm', 'o']: potential_keys.append(xor(item, k)) # Unique potential keys. potential_keys = list(set(potential_keys)) print('Repeated letters found. Only relevant keys added.') print('Current potential keys:', potential_keys) print('Current number of potential keys:', len(potential_keys)) # removes potential keys which are not printable characters for k in potential_keys: if not converters.valid_characters(k): potential_keys.remove(k) print('Current number of potential keys:', len(potential_keys)) print('Current potential keys:', potential_keys) else: for k in range (32,127): potential_keys.append(chr(k))