Skip to content

Instantly share code, notes, and snippets.

@yarjor
Last active March 26, 2018 18:18
Show Gist options
  • Select an option

  • Save yarjor/c64a5020019be1877d5f28bda6a2f3ff to your computer and use it in GitHub Desktop.

Select an option

Save yarjor/c64a5020019be1877d5f28bda6a2f3ff to your computer and use it in GitHub Desktop.
[Break repeating-key XOR encryption] #crypto #xor
from break_single_key import break_single_key
def get_block(msg, length, index=0):
return msg[length * index : length * (index + 1)]
def break_repeating_by_keysize(msg, keysize):
blocks = [get_block(msg, keysize, i) for i in xrange(len(msg) / keysize)]
transposed_blocks = zip(*blocks)
full_key = ''
for trans in transposed_blocks:
_, key = break_single_key(trans, True)
full_key += key
return repeating_key_xor(msg, full_key), full_key
def guess_keysize(msg, size_range=range(2, 45), return_options=5):
key_size_hamming = []
for keysize in size_range:
blocks = [get_block(msg, keysize, i) for i in xrange(len(msg) / keysize)]
hammings = [calc_hamming(block, blocks[index*2 +1]) / float(keysize) for index, block in enumerate(blocks[::2]) if index*2 < len(blocks)]
avg_ham = sum(hammings) / float(len(hammings))
key_size_hamming.append((keysize, avg_ham))
key_size_hamming.sort(key=lambda x: x[1])
return key_size_hamming[:return_options]
def break_repeating_key(msg, quality_test, size_range=range(2, 45), range_options=5):
optional_sizes = guess_keysize(msg, size_range, range_options)
possible_solutions = [break_repeating_by_keysize(msg, i) for i in optional_sizes]
possible_solutions.sort(key=lambda x: quality_test(x[0]))
return possible_solutions[0]
def break_single_key(msg, quality_test, return_key=False):
possible_outputs = []
for key in map(chr, xrange(256)):
out = repeating_key_xor(msg, key)
possible_outputs.append((key, out))
possible_outputs.sort(key=lambda x: quality_test(x[-1]))
res = possible_outputs[0]
if return_key:
return res[::-1]
return res[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment