scytale.py


SUBMITTED BY: siriarah

DATE: Feb. 19, 2022, 7:02 p.m.

FORMAT: Python 3

SIZE: 1.9 kB

HITS: 344

  1. # -*- coding: utf-8 -*-
  2. from cipher import Cipher
  3. """ Implementacao da Cifra Scytale """
  4. class Scytale(Cipher):
  5. def encrypt(self, plaintext, key):
  6. ''' Cifra o texto com a cifra scytale utilizando a chave key. '''
  7. square = []
  8. plaintext = self.format_str(plaintext)
  9. idx = 0
  10. lines = len(plaintext) // key
  11. if len(plaintext) % key:
  12. lines += 1
  13. for lin in range(lines):
  14. square.append([])
  15. for col in range(key):
  16. if len(plaintext) > idx:
  17. square[lin].append(plaintext[idx])
  18. else:
  19. square[lin].append('')
  20. idx += 1
  21. ciphertext = ''.join([square[lin][col] for col in range(key) for lin in range(lines)])
  22. return ciphertext
  23. def decrypt(self, ciphertext, key):
  24. ''' Decifra o ciphertext com a cifra Scytale usando a chave key. '''
  25. idx = 0
  26. ciphertext = self.format_str(ciphertext)
  27. lines = len(ciphertext) // key
  28. if len(ciphertext) % key:
  29. lines += 1
  30. # quantidade de colunas completas
  31. spaces = len(ciphertext) % key
  32. square = [['' for col in range(key)] for lin in range(lines)]
  33. for col in range(key):
  34. for lin in range(lines):
  35. if len(ciphertext) > idx:
  36. if not spaces and lin >= lines - 1:
  37. # executa caso a coluna ao seja completa
  38. square[lin][col] = ''
  39. idx -= 1
  40. else:
  41. square[lin][col] = ciphertext[idx]
  42. idx += 1
  43. if spaces:
  44. spaces -= 1
  45. plaintext = ''.join([square[lin][col] for lin in range(lines) for col in range(key)])
  46. return plaintext

comments powered by Disqus