Cifra de Trithemius ou tabula Recta em Python


SUBMITTED BY: Guest

DATE: Aug. 19, 2014, 4:20 p.m.

FORMAT: Python

SIZE: 1.3 kB

HITS: 1549

  1. # -*- coding: utf-8 -*-
  2. import string
  3. class Trithemius(object):
  4. '''
  5. Classe de cifra Trithemius
  6. '''
  7. def __init__(self):
  8. self.plain = string.ascii_uppercase
  9. self.cipher = string.ascii_uppercase
  10. def shift(self):
  11. '''
  12. Desloca o alfabeto cifrado em uma casa.
  13. '''
  14. self.cipher = self.cipher[1:] + self.cipher[:1]
  15. def encrypt(self, text, decrypt=False):
  16. '''
  17. Cifra text com a cifra de Trithemius.
  18. Se decrypt é True, decifra ao invés de cifrar o text.
  19. '''
  20. text = text.replace(' ', '')
  21. ret_text = ''
  22. for char in text.upper():
  23. if decrypt:
  24. idx = self.cipher.find(char)
  25. ret_text += self.plain[idx]
  26. else:
  27. idx = self.plain.find(char)
  28. ret_text += self.cipher[idx]
  29. self.shift()
  30. self.cipher = string.ascii_uppercase
  31. return ret_text
  32. def decrypt(self, text):
  33. '''
  34. Decifra text com a cifra de Trithemius.
  35. '''
  36. return self.encrypt(text, True)

comments powered by Disqus