Created
June 28, 2015 07:26
-
-
Save checkaayush/e0c16e32e40dcfb96beb to your computer and use it in GitHub Desktop.
Decrypt Chinese Transposition Ciphers.
This file contains hidden or 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
# Solving Chinese Columnar Transposition Cipher | |
list_of_words = ['KLTNS AUEIA RDNHC', 'NABEK TYRBO', 'ENDTW YSILA', | |
'OJS BET SVE', 'RASRF EUQUO', 'TAB EGI SLL', 'KMNE SUOL', | |
'OONC DRAR LOII ANTS', 'IENIREA NTSETBL', 'OSAJAHM NKCLECI'] | |
def solve_chinese_cipher(cipher_text): | |
""" Given encrypted cipher_text, returns decrypted secret_message.""" | |
components = cipher_text.split(' ') | |
# print components | |
num_components = len(components) | |
# print "num_components = ", num_components | |
component_length = len(components[0]) | |
# print "component_length = ", component_length | |
cipher_matrix = [] | |
for component in components: | |
cipher_matrix.append(list(component)) | |
decrease_i = False | |
total_letters = component_length * num_components | |
count_letters = 1 | |
once_more = False | |
i = 0 | |
j = component_length - 1 | |
secret_message = [cipher_matrix[i][j]] | |
index = 0 | |
while j >= 0: | |
while i >= 0: | |
if once_more: | |
secret_message.append(cipher_matrix[i][j]) | |
count_letters += 1 | |
if decrease_i: | |
i -= 1 | |
else: | |
i += 1 | |
if i == 0: | |
secret_message.append(cipher_matrix[i][j]) | |
count_letters += 1 | |
decrease_i = False | |
if not once_more: | |
once_more = True | |
j -= 1 | |
elif i == (num_components - 1): | |
secret_message.append(cipher_matrix[i][j]) | |
count_letters += 1 | |
decrease_i = True | |
if not once_more: | |
once_more = True | |
j -= 1 | |
else: | |
secret_message.append(cipher_matrix[i][j]) | |
count_letters += 1 | |
once_more = False | |
if count_letters == total_letters: | |
break | |
if j == 0 and (count_letters == total_letters): | |
break | |
index += 1 | |
secret_message = "".join(secret_message) | |
return secret_message | |
def main(): | |
for cipher_text in list_of_words: | |
secret_message = solve_chinese_cipher(cipher_text) | |
print secret_message | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment