def single_byte_xor_break(hexstring): """Try to decrypt a hex strings that has been encrypted with a one Byte key :param hexstring: The hex encoded, one Byte XOR encrypted data to brute force :return: A tuple containing the key at position 0 and the decrypted string at position 1. """ hexstring_bytes = hexstring_to_bytelist(hexstring) # Try every byte counting the number of letters for each decrypt best_guess_num_letters = None best_guess = None best_guess_key = None for i in xrange(0, 255): decrypt = [chr(byte ^ i) for byte in hexstring_bytes] num_letters = sum(1 for c in decrypt if c.isalpha() or c.isspace()) # We'll assume the guess that decrypts to the maximum number # of letters is the correct guess if num_letters > best_guess_num_letters: best_guess_num_letters = num_letters best_guess = ''.join(decrypt) best_guess_key = i return best_guess_key, best_guess
def test_hexstring_to_bytelist(): assert cc_util.hexstring_to_bytelist('01020304050a0b0c0d10') == [1, 2, 3, 4, 5, 10, 11, 12, 13, 16]