Created
January 25, 2018 22:03
-
-
Save WPettersson/0f214255e765459af3ca786be86df340 to your computer and use it in GitHub Desktop.
Brute forcing some vigenere cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
def main(): | |
words = {} | |
with open("words", "r") as wordfile: | |
for line in wordfile: | |
if len(line.rstrip()) in [2, 3, 4, 5]: | |
words[line.rstrip()] = True | |
cipher = [[7, 16], [24, 26], [3, 8, 19, 5], [5, 24, 25, 13], | |
[24, 23, 7, 18], [2, 8, 12], [13, 21, 2, 8, 19], | |
[18, 2, 23], [26, 26, 8, 26], [26, 25, 9, 11], | |
[2, 15, 25], [21, 20, 7, 9, 13]] | |
key_length = 1 | |
best = 0 | |
num_words = len(cipher) | |
key = [0] * key_length | |
while True: | |
key_index = 0 | |
plain = 0 | |
plain_words = [] | |
for word in cipher: | |
plain_word = "" | |
for letter in word: | |
new_letter = chr(97+((letter + key[key_index]) % 26)) | |
plain_word += new_letter | |
key_index = (key_index + 1) % key_length | |
plain_words.append(plain_word) | |
if plain_word in words.keys(): | |
plain += 1 | |
ratio = plain/num_words | |
if ratio > best: | |
print("".join([chr(97+l) for l in key]), | |
" | ", " ".join(plain_words), ratio) | |
best = ratio | |
updated = key_length - 1 | |
while True: | |
key[updated] += 1 | |
key[updated] = key[updated] % 26 | |
if key[updated] != 0: | |
break | |
updated -= 1 | |
if updated == -1: | |
key_length += 1 | |
key = [1] * key_length | |
print("Key length is %d" % key_length) | |
break | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment