Skip to content

Instantly share code, notes, and snippets.

@Browne
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save Browne/1a18e4c63a7e82bb5eb0 to your computer and use it in GitHub Desktop.

Select an option

Save Browne/1a18e4c63a7e82bb5eb0 to your computer and use it in GitHub Desktop.
Basic transposition cracker. Added method to check for THE in text (quicker than scouring the dictionary). Added method to strip \r \n chars from the output.
#!/usr/bin/env python
import math
def getStrings(file1):
"Get the string from the file"
with open(file1, 'r') as a:
b = a.readlines()
return (''.join(b))
def decrypt(x, y):
"""x = key
y = message
Get num of columns from key"""
numColumns = int(math.ceil(len(y) / x))
whiteSpace = (numColumns * x) - len(y) #White space at end of table
text = [''] * (numColumns + 1) #Create array correct size
col = 0
row = 0
for c in y:
"Loop over characters (c) in y. Add to array at index[column]"
text[col] += c
col = int(col + 1 % numColumns)
if (col == int(numColumns)) or ((col == numColumns - 1) and (row >= x - whiteSpace)):
"""If column exceeds correct value, start again."""
col = 0
row += 1
solution = ''.join(text).strip('\n') #Remove stray newline that appears for some reason
return solution
if __name__ == '__main__':
file1 = raw_input("Enter file with cipher text: ")
y = getStrings(file1)
for x in range(4, 9, 1):
"""Loop between 4-8 to find the solution"""
solution = decrypt(int(x), y)
#Likely to contain THE.
if "THE" in solution:
print (int(x))
print (solution.strip('\r'))
#Another attempt to remove god damn new line char
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment