def breakxor(raw, keysize=-1): if(keysize == -1): distances = get_probable_key_sizes(raw) else: diff = get_normalized_distance(raw, keysize, 4) distances = [Distance(keysize, diff)] best_decrypted = None best_score = None for dist in distances: keysize = dist.keysize blocks = [[] for _ in range(keysize)] for i in range(0, len(raw)): pos = i % keysize blocks[pos].append(raw[i]) key = bytearray() for block in blocks: b, output, score = solve_xor_block(block) key.append(b) decrypted = xor_repeating(raw, key) score = frequency.scoreof(decrypted) if( best_score is None or score < best_score): best_decrypted = (key, decrypted) best_score = score return best_decrypted
def solve_xor_block(encoded_bytes): current_score = 0 current_byte = None current_bytes = None for b in range(0, 256): test_byte = bytes([b])[0] decoded_bytes = xor_against_byte(encoded_bytes, test_byte) score = frequency.scoreof(decoded_bytes) if current_score == 0 or score < current_score: current_score = score current_byte = test_byte current_bytes = decoded_bytes return (current_byte, current_bytes, current_score)