Last active
January 31, 2016 00:04
-
-
Save k3an3/44115928cf5af257e886 to your computer and use it in GitHub Desktop.
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
from math import gcd | |
lines = [] | |
groups = [] | |
english_freq = "etaoinshrdlcumwfgypbvkjxqz" | |
ct = "" | |
def get_gcds(): | |
# Assemble groups of 4 letters | |
for i in range(3, len(ct)): | |
groups.append(ct[i-3] + ct[i-2] + ct[i-1] + ct[i]) | |
# Assemble groups of 3 letters | |
for i in range(2, len(ct)): | |
groups.append(ct[i-2] + ct[i-1] + ct[i]) | |
s = [] | |
# Find repeated groups and record the distance between them | |
for n, group in enumerate(groups): | |
try: | |
s.append(groups.index(group, n + 1) - n) | |
except ValueError: | |
pass | |
except IndexError: | |
pass | |
gcds = [] | |
# Find the greatest common denominators present in the distances | |
for n, num in enumerate(s): | |
gcds.append(gcd(s[n-1], s[n])) | |
gcds = list(set(gcds)) | |
gcds.sort() | |
gcds.remove(1) | |
print() | |
print("Possible key sizes:") | |
print(gcds) | |
print("Guessed key size:") | |
print(min(gcds)) | |
return min(gcds) | |
def freq_analysis(keysize): | |
print() | |
letters = {} | |
key = "" | |
# Fill the dict with the alphabet | |
ct_groups = [ct[i:i+keysize] for i in range(0, len(ct), keysize)] | |
for n in range(0, keysize): | |
for i in range(0, 26): | |
letters[chr(ord('a') + i)] = 0 | |
for group in ct_groups: | |
if len(group) == keysize: | |
letters[group[n]] += 1 | |
sort = [letter[0] for letter in sorted(letters.items(), key=lambda x: x[1], reverse=True)] | |
distance = (ord(english_freq[sort.index('e')]) - ord('a')) % 26 | |
key += chr(ord('a') + distance) | |
print("Found key with size", keysize, ":", key) | |
return key | |
def decode(key): | |
plaintext = "" | |
for n, letter in enumerate(ct): | |
val = (ord(letter) - ord(key[n % len(key)]) + 1) - 1 | |
print(val) | |
if val < 0: | |
plaintext += chr(26 + val + ord('a')) | |
else: | |
plaintext += chr(val + ord('a')) | |
print(plaintext) | |
if __name__ == "__main__": | |
with open("ciphertext.txt") as f: | |
print("Ciphertext:") | |
for n, line in enumerate(f): | |
print(n, line.replace("\n", "")) | |
lines.append(line.replace("\n", "")) | |
ct = ''.join(lines) | |
decode("mindtrick") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment