Skip to content

Instantly share code, notes, and snippets.

@gamorales
Last active June 5, 2020 16:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamorales/1cc5b5dd789f37774d2b227916fa0364 to your computer and use it in GitHub Desktop.
Save gamorales/1cc5b5dd789f37774d2b227916fa0364 to your computer and use it in GitHub Desktop.
Encrypt a text and concatenating the resultant text with itself by characters sorted
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Encrypt and Decrypt idea extracted from http://rodrigogr.com/blog/cifrado-de-transposicion/
import math
def main():
text_encrypt = 'Guillermo Alfonso Morales, 1983-02-12, Santiago de Cali'
key_length = int(len(text_encrypt) / 4)
cipher_text = encrypt_text(key_length, text_encrypt)
print(cipher_text)
plain_text = decrypt_text(key_length, cipher_text)
print(plain_text)
def encrypt_text(key, text):
""" Encripts a text
:param key: number of cols for the matriz
:param text:
:return:
"""
# Columns at matriz
cipher_text = [''] * key
for col in range(key):
pointer = col
while pointer < len(text):
# The character will be saved with 'key' plus in ascii value
cipher_text[col] += chr(ord(text[pointer])+key)
pointer += key
# New lists with characters ordered ascending
sorted_text = list(''.join(cipher_text))
sorted_text.sort()
# Concatenate both lists
for i, v in enumerate(list(''.join(cipher_text))):
sorted_text.insert(2 * i + 1, v)
return ''.join(sorted_text)
def decrypt_text(key, text):
""" Decrypts a matriz
:param key: number of cols for the matriz
:param text: Cipher Text to convert text
:return:
"""
# text only with the correct values
text = [text[_] for _ in range(1, len(text), 2)]
text = ''.join(text)
# Number of columns and rows for the matriz
num_columns = math.ceil(len(text) / key)
num_rows = key
# Empty cells quantity in the matriz
num_empty_cells = (num_columns * num_rows) - len(text)
plain_text = [''] * num_columns
col = 0
row = 0
for symbol in text:
plain_text[col] += chr(ord(symbol)-key)
col += 1
# If not cols or empty cell, then next row
if (col == num_columns) or (col == num_columns - 1 and row >= num_rows - num_empty_cells):
col = 0
row += 1
return ''.join(plain_text)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment