Cifra rail fence em Python


SUBMITTED BY: Guest

DATE: July 5, 2013, 7:35 p.m.

FORMAT: Text only

SIZE: 1.7 kB

HITS: 1629

  1. class Railfence:
  2. def __railfence_id(self, tam, key):
  3. ''' (Railfence, int, int) -> list of int
  4. Retorna um lista de inteiros com a posicao da linha que o caracter do texto ira ocupar, variando de 0 ate key - 1.
  5. '''
  6. j = 0
  7. inc = 0
  8. idx = []
  9. for i in range(tam):
  10. if j == key - 1:
  11. inc = -1
  12. elif j == 0:
  13. inc = 1
  14. idx.append(j)
  15. j += inc
  16. return idx
  17. def encrypt(self, texto, key):
  18. ''' (Railfence, str, int) -> str
  19. Retorna o texto plano cifrado na cifra rail fence com a chave key.
  20. '''
  21. texto = texto.replace(' ', '')
  22. tam = len(texto)
  23. idx = self.__railfence_id(tam, key)
  24. cifrado = ''
  25. for i in range(key):
  26. for z in range(tam):
  27. if idx[z] == i:
  28. cifrado += texto[z]
  29. return cifrado.upper()
  30. def decrypt(self, texto, key):
  31. ''' (Railfence, str, int) -> str
  32. Retorna o texto plano para um texto cifrado com a cifra rail fence com a chave key.
  33. '''
  34. texto = texto.replace(' ', '')
  35. tam = len(texto)
  36. idx = self.__railfence_id(tam, key)
  37. idx_sorted = sorted(idx)
  38. texto_plano = ''
  39. for i in range(tam):
  40. for j in range(tam):
  41. if idx[i] == idx_sorted[j] and idx[i] > -1:
  42. texto_plano += texto[j]
  43. idx[i] = -1
  44. idx_sorted[j] = -1
  45. return texto_plano.lower()

comments powered by Disqus